Search code examples
c++c++11constantsplacement-new

Use placement new to create a static const pointer to a static memory buffer


I'd like to initialize a static, constant pointer to an object of class type MyClass2, which is stored in a static data buffer in class MyClass1 when it is instantiated.

This doesn't work:

class MyClass1 {
   public:
       MyClass1()
       {
           _my_class_2_ptr = new (_my_class_2_buf) MyClass2();
       }

   private:
      static MyClass2 *const  _my_class_2_ptr;
      static char *_my_class_2_buf = new char[sizeof(MyClass2)]; 
};

Is there a way to accomplish something like this?


Solution

  • When your variables are static, you can't initialize them in constructor. It just doesn't make sense! What you want to do is something like

    (in header)

    class MyClass1 {
       // member    
       public:
          static MyClass2 *const  _my_class_2_ptr;
          static std::aligned_storage_t<sizeof(MyClass2)> _my_class_2_buf; 
    };
    

    (in cpp)

    std::aligned_storage_t<sizeof(MyClass2)> MyClass1::_my_class_2_buf;
    MyClass2* const MyClass1::_my_class_2_ptr = new (&MyClass1::_my_class_2_buf) MyClass2;