从向量复制<指针*>到向量<指针*>在 C++ 中 [英] Copy from vector<pointer*> to vector<pointer*> in C++
问题描述
我创建了一个向量 A 并想使用以下方法复制到另一个类中的向量 B,这是正确的方法吗?向量 A 可能会被破坏!我在谷歌搜索,但没有找到好的解决方案和有意义的解释.谢谢大家
void StateInit(vector listBtn){_m_pListBtn = listBtn;};
是与否,您正在按值传递向量:
void StateInit(vector listBtn){_m_pListBtn = listBtn;};
这意味着 listBtn 是向量 A 的副本(假设我们正在调用作为 StateInit 参数传递的向量 A),如果删除向量 A,向量 B 仍将拥有指针集合,并且它们将有效,因为指针向量的销毁不会删除指向的对象,因为现在不可能如何(应该调用、删除、删除 []、释放?).
请记住,如果您修改/删除向量 A 中的元素之一(使用向量上的指针),则该元素将在向量 B 中修改(因为它是指向同一元素的指针).>
我不确定你的意图是什么,但如果你想复制整个向量,你应该为对象实现一个克隆机制,然后使用变换复制它们:
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 everyone
void 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++ 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!