Defining an object without calling its constructor in C++

后端 未结 7 2151
执笔经年
执笔经年 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

    You can fully control the object construction and destruction by this trick:

    template
    struct DefferedObject
    {
        DefferedObject(){}
        ~DefferedObject(){ value.~T(); }
        template
        void Construct(TArgs&&...args)
        {
            new (&value) T(std::forward(args)...);
        }
    public:
        union
        {
            T value;
        };
    };
    

    Apply on your sample:

    class Program
    {
    public:
       DefferedObject myObject; //Should not try to call the constructor or do any initializing
       Program()
       {
          ...
    
          //Now call the constructor
          myObject.Construct(....);
       }
    
    }
    
    
    

    Big advantage of this solution, is that it does not require any additional allocations, and object memory allocated as normal, but you have control when call to constructor.

    Another sample link

    提交回复
    热议问题