Defining an object without calling its constructor in C++

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

    If you have access to boost, there is a handy object that is provided called boost::optional<> - this avoids the need for dynamic allocation, e.g.

    class foo
    {
      foo()  // default std::string ctor is not called..
      {
        bar = boost::in_place("foo"); // using in place construction (avoid temporary)
      }
    private:
      boost::optional bar;
    };
    

提交回复
热议问题