假设我有一个std::optional<Foo>对象。我想调用其值的方法( 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 */是否包括一个条件(test)和一个方法(test-> method ()),它们依赖于这个条件(test)是否在相同的条件语句中是正确的?,这是糟糕的编码礼仪吗?
发布于 2018-08-09 18:27:46
你要找的是一个“解除引用,如果不是零”运算符。C++没有这样的运算符。
有些语言确实有这个运算符。如果C++采用了来自C#的?.操作符,然后让std::optional重载它,那么代码就是这样的:
std::optional<foo> test = might_return_a_foo();
//If empty, short-circuit and stop. If not null, call method()
test?.method();我不认为写显式检查有什么问题,尽管有一个正确的解除引用-如果不是-空运算符。如果您能够确信所讨论的对象将存在,则不会从函数返回optional;您只需返回一个对象并避免此问题。对象可能不存在这一事实是很重要的,最好让程序员为这个场景编写显式处理。
值得注意的是,您可以使事情变得更简洁一些,尽管:
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;
}这段代码非常有效地处理检查,optional对象在if块中是可见的当且仅当该对象实际存在;如果它不存在,那么您可能不需要空的optional对象。
https://stackoverflow.com/questions/51773258
复制相似问题