gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:00:37 28 4
gpt4 key购买 nike

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;
}
编译该代码时,我们会获得 returning reference to temporary警告原因 value_or按值返回。
有没有办法返回一个常量引用?

最佳答案

value_or按值返回。已经是拷贝了。你必须自己做。

const bool& GetValue() { return mValue ? mValue.value() : mDefault; }

关于c++ - 如何从 std::optional::value_or 返回常量引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64205492/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com