Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a destructor destroy a static member?

Tags:

c++

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?

like image 547
sickgemini Avatar asked May 24 '10 02:05

sickgemini


People also ask

Can a destructor be static?

class X { public: // Constructor for class X X(); // Destructor for class X ~X(); }; A destructor takes no arguments and has no return type. Its address cannot be taken. Destructors cannot be declared const , volatile , const volatile or static .

How do you destroy a static variable in C++?

Encapsulate your pointer into a class (as member), then use this class as the type of your static. That way, you know the class destructor will be called at the end of the application. You then just delete your data in the destructor and the work is done and clean.

Can we delete static memory?

don't delete it; in most cases, there's really no reason to call the destructor, and if you happen to use the instance in the destructors of other static objects, you'll run into an order of destruction problem.

Can object be static in C++?

C++ also supports static objects.


2 Answers

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.

like image 69
futureelite7 Avatar answered Sep 20 '22 15:09

futureelite7


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.

like image 37
Matthew Flaschen Avatar answered Sep 19 '22 15:09

Matthew Flaschen