【问题标题】:Use placement new to create a static const pointer to a static memory buffer使用placement new 创建一个指向静态内存缓冲区的静态常量指针
【发布时间】:2016-06-22 17:24:44
【问题描述】:

我想初始化一个指向 MyClass2 类类型对象的静态常量指针,该对象在实例化时存储在 MyClass1 类的静态数据缓冲区中。

这不起作用:

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)]; 
};

有没有办法完成这样的事情?

【问题讨论】:

    标签: c++ c++11 constants placement-new


    【解决方案1】:

    当你的变量是静态的,你不能在构造函数中初始化它们。这只是没有意义!你想要做的是像

    (在标题中)

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

    (在 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;
    

    【讨论】:

    • 明白。由于静态变量对类来说是通用的,我想每次实例化类时重新初始化它们是没有意义的。但是,在这种情况下,我希望 MyClass1 成为单例,因此无论如何它只能实例化一次,我想这并不重要。
    • 您缺少 type 的 std::aligned_storage::type - 非常糟糕!
    • @DieterLücking 他使用的是aligned_storage_t 而不是aligned_storage
    • @DieterLücking,我不是 :)(至少在声明中)
    • 不管怎样,你不需要std::aligned_storage_t,一个普通的char storage[sizeof(MyClass2)];也可以。
    【解决方案2】:

    您可以将static 成员变量的定义和初始化移到类之外。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-12
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 2012-02-26
      相关资源
      最近更新 更多