Copy from vector<pointer*> to vector<pointer*> in C++

丶灬走出姿态 提交于 2020-01-01 11:11:09

问题


I create a vector A and want to copy to a vector B in another class by using below method, is it a correct way? The vector A may be destroyed! I searched in google, but not found the good solution and meaningful explanation. Thanks everyone

void  StateInit(vector<CButton*> listBtn) 
{ 
   _m_pListBtn = listBtn; 
 };

回答1:


Yes and no, you are passing the vector by value:

void  StateInit(vector<CButton*> listBtn) 
{ 
   _m_pListBtn = listBtn; 
 };

Wich means that listBtn is a copy of vector A (asuming we are calling vector A the one passed as parameter of StateInit), if you delete vector A, vector B will still have the collection of pointers and they will be valid since the destruction of a vector of pointers doesnt delete the pointed objects because it cant possible now how (should it call, delete, delete[], free?).

Do keep in mind that if you modify/delete one of the elements from vector A (using the pointers on the vector), that element will be modified in vector B (since its a pointer to the same element).

Im not sure what is your intend with this, but if you want to copy the whole vector, you should implement a clone mechanism for the objects and then copy them using transform:

class cloneFunctor {
public:
    T* operator() (T* a) {
        return a->clone();
    }
}

Then just:

void  StateInit(vector<CButton*> listBtn) 
{ 
   transform(listBtn.begin(), listBtn.end(), back_inserter(_m_pListBtn), cloneFunctor()); 
 };

IF your intention is not to clone it but to share the pointers you should pass the vector as pointer or reference:

void StateInit(const vector<CButton*>& listBtn) 
{ 
   _m_pListBtn = listBtn; 
};



回答2:


A better way is to iterate on the new vector and push_back the elements to your vector.

See example code: std::vector::begin



来源:https://stackoverflow.com/questions/16475042/copy-from-vectorpointer-to-vectorpointer-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!