Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在可选结构memeber中分配成员_C++_Boost Optional - Fatal编程技术网

C++ 在可选结构memeber中分配成员

C++ 在可选结构memeber中分配成员,c++,boost-optional,C++,Boost Optional,指定结构的可选成员的最佳样式是什么? 例如,我有一个结构: struct B{ public: int x; } struct A{ public: boost::optional<B> b; }; void foo(){ A a; a.b.x = 10; //Runtime exception because a.b is not initialized. } 或: 有没有更清晰的方法 您别无选择,只能在使用它之前初始化它。如果不这样做,您将

指定结构的可选成员的最佳样式是什么? 例如,我有一个结构:

struct B{
public:
    int x;
}


struct A{
public:
    boost::optional<B> b;
};


void foo(){
   A a;
   a.b.x = 10; //Runtime exception because a.b is not initialized. 
}
或:


有没有更清晰的方法

您别无选择,只能在使用它之前初始化它。如果不这样做,您将有一个断言失败,这将导致终止

但是,如果您询问初始化它的方法,有很多:

  • a.b=b{10}
  • a.b=b()
  • 创建一个构造函数,使其类似于
    a.b=b(10)
    。但是,您始终必须创建一个对象并将其指定给它。因此,可以隐式或显式创建对象,但必须这样做
  • 在中,@n.m告诉我们,这里有一个
    emplace()
    方法,它对您也有同样的作用:
    a.b.emplace()

  • 您别无选择,只能在使用它之前初始化它。如果不这样做,您将有一个断言失败,这将导致终止

    但是,如果您询问初始化它的方法,有很多:

  • a.b=b{10}
  • a.b=b()
  • 创建一个构造函数,使其类似于
    a.b=b(10)
    。但是,您始终必须创建一个对象并将其指定给它。因此,可以隐式或显式创建对象,但必须这样做
  • 在中,@n.m告诉我们,这里有一个
    emplace()
    方法,它对您也有同样的作用:
    a.b.emplace()

  • 在你的例子中:
    a.b=b{10}
    @m.s.如果B更复杂?你的第一个例子不是临时的。在你的例子中:
    a.B=B{10}@m.s.如果B更复杂,你的第一个例子不是临时的。
    
    void foo(){
        A a;
        B tmp;
        a.b = tmp;
        a.b.x = 10; //OK. 
    }
    
    void foo(){
        A a;
        a.b = B();
        a.b.x = 10; //OK. 
    }