I was wondering which part of my code will free a dynamically allocated, but static class member when this is not needed anymore. See the following code: classPrinter is shared among all A-objects and created when the first instance of class A will be created. Just to be sure: the classPrinter-object will automatically be destructed when exiting my program, right?
a.h
class A {
static B* classPrinter;
}
a.cpp
#include "a.h"
B A::classPrinter = new B();
A::A() { ...}
Since this is C++, the answer is “No.” For everything allocated with
newthe correspondingdeletemust be called. If that doesn’t happen, the object leaks. But why allocate this dynamically at all? Thisbehaves like your code, except that
classPrinterwill be destructed at the end of the program.However, you write that
The code in your question doesn’t do this. If you want to do this, do something like this:
The smart pointer will make sure that the object gets deleted.