Talesseed Talesseed - 1 year ago 81
C++ Question

C++ - Object destructed when out of scope and in vector

Why is the destructor of an object called when it goes out of scope and when it is in a vector ?
For example :

std::vector<Foo> vec;
for (i=10; i<10; i++)
Foo object(i);

Is the destructor of object called because it goes each time out of scope? Can I make it work without pointers or shared_pointers?

Asu Asu
Answer Source

object will die out of this scope, this is correct. No, vector doesn't and couldn't affect its lifetime. push_back actually copies object into the vector. To avoid this, you can use C++11's emplace_back which allows to construct Foo in-place:


This test program confirms no copy, move or extra destruction is performed.

Constructing A
End of vec's scope
Destructing A
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download