c++ - Does push_back in vector insert at the same location? -
class example { public: int i; example(const example &e) { = 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; --> 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"; } }
the above code prints foobar2 twice. shouldn't print foobar1 , foobar2? also, best way copy vector containing objects? want deep copying.
for(int i=0; i<vec.size(); ++i) // --> deep copy { example newe(*(vec[i])); newvec.push_back(&newe); }
in code make copy of vec[i]
example newe
. push_back
address of newe
newvec
vector. newe
object goes out of scope , destroyed, end having pointer garbage inside newvec
.
if want deep copy of vector content, and want store owning pointers objects, consider using vector of smart pointers, e.g. vector<shared_ptr<example>>
.
in case, can copy vectors operator=
, , reference counts of shared_ptr
s automatically updated.
yoy may want consider simpler design of having vector<example>
(without pointer indirection).
Comments
Post a Comment