What is the lifetime of a C++ class member. For example, at which time will the std::fstream
of a Foo
object be released? When entering the destructor or when leaving the destructor? Is this defined in the C++ standard?
struct Foo
{
std::fstream mystream;
~Foo()
{
// wait for thread writing to mystream
}
};
The mystream
data member is destroyed during the destruction of the Foo
object, after the body of ~Foo()
is executed. C++11 §12.4[class.dtor]/8 states:
After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class
X
calls the destructors forX
's direct non-variant non-static data members, the destructors forX
's direct base classes and, ifX
is the type of the most derived class, its destructor calls the destructors forX
's virtual base classes.
mystream
is a non-variant, non-static data member of Foo
(a variant data member is a member of a union; Foo
is not a union).