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?另外,这是复制包含对象的矢量的最佳方法吗?我想深刻复制.