简体   繁体   English

从向量复制 <pointer*> 矢量 <pointer*> 在C ++中

[英]Copy from vector<pointer*> to vector<pointer*> in C++

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? 我创建了一个向量A,并想使用下面的方法复制到另一个类的向量B中,这是正确的方法吗? The vector A may be destroyed! 向量A可能被破坏! I searched in google, but not found the good solution and meaningful explanation. 我在google中搜索,但未找到好的解决方案和有意义的解释。 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?). Wich表示listBtn是向量A的副本(假定我们将向量A称为StateInit的参数传递),如果删除向量A,向量B仍将具有指针的集合,并且自从销毁后就有效。指针向量不会删除所指向的对象,因为它现在不可能(应该调用,删除,删除[],释放吗?)。

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). 请记住,如果您修改/删除了向量A中的一个元素(使用向量上的指针),则该元素将在向量B中被修改(因为它指向相同元素的指针)。

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: 我不确定这是什么打算,但是如果要复制整个矢量,则应为对象实现克隆机制,然后使用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; 
};

A better way is to iterate on the new vector and push_back the elements to your vector. 更好的方法是迭代新向量,并将元素push_back回向量中。

See example code: std::vector::begin 参见示例代码: std :: vector :: begin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM