Lifetime of C++ class members
Asked Answered
A

2

7

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
    }
};
Anarchism answered 6/10, 2012 at 22:5 Comment(0)
J
12

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).

Justly answered 6/10, 2012 at 22:8 Comment(0)
E
3

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

Elder answered 6/10, 2012 at 22:13 Comment(3)
what if class member is a pointer to one local member? string *name , then name is the pointer that declared in one method, out of method name will be destroyed then how about the class's *name ?Josettejosey
@TomSawyer: Doesn't matter what it points at. The pointer itself is still a data member.Elder
I know, but it it will become dangling pointer, since the memory address it pointed to has been deallocated after out of scope.Josettejosey

© 2022 - 2024 — McMap. All rights reserved.