Talesseed Talesseed - 5 months ago 29
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

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