简体   繁体   English

如何从 std::optional::value_or 返回常量引用?

[英]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.

相关问题 std :: optional :: value_or() - 懒惰参数评估 - std::optional::value_or() - lazy argument evaluation 有什么阻止std :: optional :: value_or()有条件地noexcept吗? - Does anything prevent std::optional::value_or() from being conditionally noexcept? 为什么const rvalue限定std :: optional :: value()返回一个const右值引用? - Why does the const rvalue qualified std::optional::value() return a const rvalue reference? 为什么 std::optional::value_or 没有默认 ctor 类型的特化? - Why std::optional::value_or dont have a specialization for default ctor types? 如何返回可选指针或引用( std::optional )? - How do I return an optional pointer or reference ( std::optional )? 将std :: string作为const引用返回 - Return std::string as const reference 防止初始化 std::optional <std::reference_wrapper<const t> > 右值 std::optional <t></t></std::reference_wrapper<const> - prevent initializing std::optional<std::reference_wrapper<const T>> with rvalue std::optional<T> 为什么std :: optional :: value()&&;返回&&? - Why std::optional::value() &&; return &&? 通过值或通过引用传递std :: chrono :: duration? - Pass std::chrono::duration by value or by reference to const? 返回值是常量引用时如何返回“未找到” - How to return "not found" when return value is const reference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM