[英]How to return const reference from std::optional::value_or?
struct A
{
static const bool mDefault = true;
std::optional<bool> mValue;
const bool& GetDefaultValue() { return mDefault; }
const bool& GetValue() { return mValue.value_or( GetDefaultValue() ); }
};
int main(int argc, char *argv[])
{
std::cout << A().GetValue() << std::endl;
}
When compile that code we obtain a returning reference to temporary
warning cause value_or
return by value.编译该代码时,我们会获得returning reference to temporary
警告原因value_or
按值返回的returning reference to temporary
。 There is a way to return a const reference?有没有办法返回一个常量引用?
value_or
returns by value. value_or
按值返回。 It's already a copy.已经是副本了。 You'll have to do it yourself.你必须自己做。
const bool& GetValue() { return mValue ? mValue.value() : mDefault; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.