Reputation: 393
I have a question about class variables and scopes in C++. Let's say I have the class below:
class TestClass {
public:
std::vector<int> v;
void foo()
{
v = std::vector<int>(10);
}
}
Now, say I call the following code:
TestClass c;
c.foo();
When is the destructor of the vector (assigned to v) called? Is it called when foo() returns or when c goes out of scope?
Upvotes: 1
Views: 718
Reputation:
Okay, let's go through this step by step:
So, v is destructed twice when c
is destructed. The temporary may will also get destructed if we have no move constructor.
Upvotes: 1
Reputation: 29724
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.
Upvotes: 2
Reputation: 7118
when your variable c goes out of scope destructor gets called automatically for c, which was automatically allocated, the destructor will take care of deleting the vector
Upvotes: 0
Reputation: 21773
v = std::vector<int>(10);
Temporary object is created, and then copied (or moved C++11) into v
. After this line, temporary object's destructor is called.
When c
goes out of scope, c.v
's destructor is called.
Note: you can also do
v.resize(10);
Upvotes: 2