Defining an object without calling its constructor in C++

后端 未结 7 2118
执笔经年
执笔经年 2020-12-23 19:26

In C++, I want to define an object as a member of a class like this:

Object myObject;

However doing this will try to call it\'s parameterle

7条回答
  •  有刺的猬
    2020-12-23 20:15

    A trick that involves anonymous union and placement new

    this is similar to jenkas' answer but more direct

    class Program
    {
    public:
       union{
       Object myObject;
       }; //being a union member in this case prevents the compiler from attempting to call the (undefined) default constructor
       
       Program()
       {
          ...
    
          //Now call the constructor
          new (&myObject) Object(...);
       }
       ~Program()
       {
          myobject.~Object(); //also make sure you explicitly call the object's destructor
       }
    
    }
    

    however the catch is that now you must explicitly define all the special member functions as the compiler will delete them by default.

提交回复
热议问题