Defining an object without calling its constructor in C++

后端 未结 7 2154
执笔经年
执笔经年 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 19:51

    Others have posted solutions using raw pointers, but a smart pointer would be a better idea:

    class MyClass {
      std::unique_ptr pObj;
      // use boost::scoped_ptr for older compilers; std::unique_ptr is a C++0x feature
    public:
      MyClass() {
        // ...
        pObj.reset(new Object(...));
        pObj->foo();
      }
      // Don't need a destructor
    };
    
    
    

    This avoids the need to add a destructor, and implicitly forbids copying (unless you write your own operator= and MyClass(const MyClass &).

    If you want to avoid a separate heap allocation, this can be done with boost's aligned_storage and placement new. Untested:

    template
    class DelayedAlloc : boost::noncopyable {
      boost::aligned_storage storage;
      bool valid;
    public:
      T &get() { assert(valid); return *(T *)storage.address(); }
      const T &get() const { assert(valid); return *(const T *)storage.address(); }
    
      DelayedAlloc() { valid = false; }
    
      // Note: Variadic templates require C++0x support
      template
      void construct(Args&&... args)
      {
        assert(!valid);
        new(storage.address()) T(std::forward(args)...);
        valid = true;
      }
    
      void destruct() {
        assert(valid);
        valid = false;
        get().~T();
      }
    
      ~DelayedAlloc() { if (valid) destruct(); }
    };
    
    class MyClass {
      DelayedAlloc obj;
    public:
      MyClass() {
        // ...
        obj.construct(...);
        obj.get().foo();
      }
    }
    
    
    

    Or, if Object is copyable (or movable), you can use boost::optional:

    class MyClass {
      boost::optional obj;
    public:
      MyClass() {
        // ...
        obj = Object(...);
        obj->foo();
      }
    };
    
        

    提交回复
    热议问题