Dhr*_*nna 0 c++ pointers vector
class Example
{
public: int i;
Example(const Example &e)
{
i = e.i;
}
Example(int i)
{
this->i = i;
}
};
int main()
{
std::vector<Example*> vec;
std::vector<Example*> newVec;
Example* ex1 = new Example(1);
Example* ex2 = new Example(2);
vec.push_back(ex1);
vec.push_back(ex2);
//newVec = vec; --> This does shallow copy
for(int i=0; i<vec.size(); ++i) // --> Deep copy
{
Example newE(*(vec[i]));
newVec.push_back(&newE);
}
for(int i=0; i<newVec.size(); ++i)
{
std::cout << "\nfoobar" << newVec[i]->i << "\n";
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码打印两次foobar2.它不应该打印foobar1和foobar2?另外,这是复制包含对象的矢量的最佳方法吗?我想深刻复制.
Run Code Online (Sandbox Code Playgroud)for(int i=0; i<vec.size(); ++i) // --> Deep copy { Example newE(*(vec[i])); newVec.push_back(&newE); }
在此代码中,您可以复制vec[i]到Example newE.然后,你push_back的地址的newE向newVec矢量.然后该newE对象超出范围并被销毁,因此您最终会有一个指向内部垃圾的指针newVec.
如果您想要矢量内容的深层副本,并且想要存储对象的拥有指针,请考虑使用智能指针向量,例如vector<shared_ptr<Example>>.
在这种情况下,您可以简单地复制向量operator=,并自动更新shared_ptrs 的引用计数.
Yoy可能还想考虑更简单的设计vector<Example>(没有指针间接).