Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return const reference from std::optional::value_or?

Tags:

c++

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. There is a way to return a const reference?

like image 600
Isaac Pascual Avatar asked Nov 01 '25 09:11

Isaac Pascual


1 Answers

value_or returns by value. It's already a copy. You'll have to do it yourself.

const bool& GetValue() { return mValue ? mValue.value() : mDefault; }
like image 112
Caleth Avatar answered Nov 03 '25 01:11

Caleth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!