Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lifetime of C++ class members

Tags:

c++

raii

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
    }
};
like image 507
Manuel Avatar asked Oct 06 '12 22:10

Manuel


2 Answers

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 for X's direct non-variant non-static data members, the destructors for X's direct base classes and, if X is the type of the most derived class, its destructor calls the destructors for X'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).

like image 99
James McNellis Avatar answered Nov 02 '22 19:11

James McNellis


It's the reverse of construction:

construction: base classes, data members (mystream constructed here), constructor body

destruction: destructor body, data members (mystream destroyed here), base classes

like image 23
Jesse Good Avatar answered Nov 02 '22 19:11

Jesse Good