Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static member variable in class with new operator

Tags:

c++

Can I declare static data member using new in C++? If we can declare static data member with new, how to initialize that static data member?

class A
{ 
    static int *p = new int;     
}

int * A :: p = 
like image 737
Sanjay Singh Avatar asked Jun 06 '26 15:06

Sanjay Singh


1 Answers

The way to go is to declare the variable inside the class and initialise it outside of it:

class A {
public:
  static int* anIntPointer; //<- declaration
};

int* A::anIntPointer = new int(42); //<- initialisation

However you would still need to clean up that memory manually since when the program ends only the pointer gets removed but the memory it points would still remain (unless your OS keeps track of the memory and cleans up after the program has ended). So call delete A::anIntPointer, e.g. at the end of main.

If you do have access to C++17 however you can declare the member inline wich allows you to directly initialise it.

class A {
public:
  inline static int* anIntPointer = new int(42); //<- declaration + initialisation
};

Anyway if you don't want to be responsible for cleaning up the memory yourself, you can use smart pointers (std::auto_ptr<> prior C++11, std::unique_ptr<> C++11 and onward).

class A {
public:
  static std::unique_ptr<int> anSmartPointer;
};

std::unique_ptr<int> A::anSmartPointer = std::unique_ptr<int>(new int(42)); // C++11
// std::unique_ptr<int> A::anSmartPointer = std::make_unique<int>(42); // or C++14 style

When the A::anSmartPointer will be destroyed at the end of your program it cleans up the memory it controls automatically.

Here you can see working examples of all the things I just explained as well as a few other things (like a C++17 inline static smart pointer).

like image 157
muXXmit2X Avatar answered Jun 09 '26 06:06

muXXmit2X