Destructor for a member vector will be called when TestClass object destructor is called. It will happen when TestClass object goes out of scope
{
TestClass c;
c.foo();
} // destructor for c calls destructor for v
This is because C++ Standard 12.6.2 § 10:
In a non-delegating constructor, initialization proceeds in the following order:
— First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
— Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
— Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
— Finally, the compound-statement of the constructor body is executed. 11 [ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. — end note ]
In line v = std::vector<int>(10)
there will be also call to destructor for temporary object, because temporary vector std::vector<int>(10)
is being created just to initialize v
, and then it is destroyed.