C++ 使用std::optional和conditionals的安全行为

C++ 使用std::optional和conditionals的安全行为,c++,C++,假设我有一个std::optional对象。我想调用一个具有其值的方法(Foo对象),但显然只有当Foo存在时才调用。我可以这样做: std::optional<Foo> test; /* stuff */ test->method(); //bad! there might not be a Foo in the optional //object depending on what happened in 'stuff' if(test)

假设我有一个
std::optional
对象。我想调用一个具有其值的方法(Foo对象),但显然只有当Foo存在时才调用。我可以这样做:

std::optional<Foo> test;

/* stuff */

test->method(); //bad! there might not be a Foo in the optional 
              //object depending on what happened in 'stuff'
if(test) {
   if (test->method()) //always valid since 'test' condition was checked
      /* do something */
}

if (test && test->method()) //is this good coding practice? 
    /* do something */
std::可选测试;
/*东西*/
测试->方法()//糟糕!选项中可能没有Foo
//对象,具体取决于“stuff”中发生的情况
如果(测试){
if(test->method())//自选中“test”条件后始终有效
/*做点什么*/
}
if(test&&test->method())//这是好的编码实践吗?
/*做点什么*/

在同一个条件语句中包含一个条件(test)和一个方法(test->method()),这取决于该条件(test)是否为true,这有关系吗?这是一种糟糕的编码礼仪吗?

您要寻找的是一个“非空时取消引用”操作符。C++没有这样的算子。 有些语言确实有这个操作符。如果C++采用了<代码> .<代码>操作符,则代码看起来会是什么样子,然后有<代码> STD:可选的< /代码>过载:

std::optional<foo> test = might_return_a_foo();
//If empty, short-circuit and stop. If not null, call method()
test?.method();

此代码非常有效地处理检查,并且当且仅当对象实际存在时,
可选
对象在
if
块内可见;如果它不存在,那么无论如何,您可能不需要空的
可选的
对象。

您可能正在寻找吗?字符串可以存在并且是空的。如果你需要检查两者,为什么不呢。我想说这是基于观点的,归根结底是可读性。由于您提到的原因,代码保证是安全的。我同意@super,这是一个主观问题。就我个人而言,我认为这种做法没有错。事实上,在上一个例子中,
if(test&&test->method())
可以被认为更干净,因为它减少了嵌套的
if
语句和缩进级别。我一直在C中看到这种代码,
if(ptr&&ptr->value>5)
if(auto opt = might_return_a_foo()) {//opt is deduced to be of type std::optional<foo>
    //This will only evaluate if opt contains a foo
    opt->method();
} else {
    //this will only evaluate if opt did NOT contain a foo
    std::cerr << "No Object to operate on." << std::endl;
}