简体   繁体   中英

Will a destructor destroy a static member?

Say I have:

class A
{
    A()
    {}
    ~A()
    {}
};

class B
{
public:
    B()
    {}
    ~B()
    {}
private:
    static A mA;
};

B* pB = new B; 
delete pB;

When I call delete pB, B's destructor will be called. Will this then call the destructor for static member A?

The keyword static means that the variable is independent of instances. That's why you can access static variables and methods without instantiating an object from the class in the first place. That's why destroying an instance will not affect any static variables.

Of course not. First of all, you've defined an explicit empty destructor. And if the default destructor did that, you could never destruct instances without risking making the class unusable.

C++ Standard 03, 9.4.2 Static data members:

A static data member is not part of the subobjects of a class. There is only one copy of a static data member shared by all the objects of the class.class.

A static data member is not part of the class -- hence it's not tied to the classes lifetime nor at construction or destruction.

Construction (9.4.2/3)

Once the static data member has been defined, it exists even if no objects of its class have been created.of its class have been created.

Destruction (9.4.2/7)

Static data members are initialized and destroyed exactly like non-local objects.

Objects with a static lifetime will be destructed when the application terminates. Among the various static objects that might be in the program, the destructors are called in the reverse order of how the objects were constructed.

The construction/destruction of object instances has no effect on when a static member is constructed or destroyed.

Static members do not live in the memory space assigned to an instance of the class. Therefore, it will not be deleted or deinitialized unless you do it explicitly in any part of your code (including the class destructor, but your code logic must handle the possibility of having multiple instances and so on...)

Static variables is also known as class variables. This is as opposed to instance variables. As these names implies, class variables pertain to the entire class, where as instance variables belong to an instance. One can derive the life span of these variables based on these facts.

Another way to look at this assume calling the destructor actually destroys static variables. Imagine then the consequence of one object gets instantiated and then gets deleted. What would happen the the static variables which are shared by all other objects of the class which are still being in used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM