Talesseed Talesseed - 1 month ago 6
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);
vec.push_back(object);
}


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

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:

vec.emplace_back(i);

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

Constructing A
End of vec's scope
Destructing A