我不确定你的意图是什么,但如果你想复制整个向量,你应该为对象实现一个克隆机制,然后使用变换复制它们:class cloneFunctor {民众:T* operator() (T* a) {返回 a->clone();}}那就:void StateInit(vector listBtn){变换(listBtn.begin(),listBtn.end(),back_inserter(_m_pListBtn),cloneFunctor());};如果您的意图不是克隆它而是共享指针,您应该将向量作为指针或引用传递:void StateInit(const vector& listBtn){_m_pListBtn = listBtn;};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 everyonevoid StateInit(vector<CButton*> listBtn){ _m_pListBtn = listBtn; }; 解决方案 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;}; 这篇关于从向量复制<指针*>到向量<指针*>在 C++ 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 08:35
查看更多