Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return const reference to const reference argument [duplicate]

Tags:

c++

Can I return a const reference argument from a function in C++? I.e., does this code lead to undefined behavior?

template<typename T>
class Option {
public:
    ...

    const T & getOrElse(const T &x) const
    {
        return val == nullptr ? x : *val;
    }

private:
    T *val = nullptr;
}

Option<Foo> foo;
foo.getOrElse(Foo());  // <- using a temporary `Foo`
like image 687
Zizheng Tai Avatar asked Mar 28 '26 08:03

Zizheng Tai


1 Answers

It's fine to return a reference as long as the object referred to is not destroyed before control leaves the function (i.e., an automatic local variable or parameter, or a temporary created inside the function).

In this case, you are potentially returning a reference to the temporary Foo() in the calling context, which is fine because that temporary is guaranteed to survive until the end of the full-expression containing the call. However, the reference would become dangling after the full-expression, i.e., the lifetime of the Foo() temporary is not extended, so care must be taken not to access it again after that point.

like image 93
Brian Bi Avatar answered Mar 29 '26 20:03

Brian Bi



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!