Teilhart
Teilhart

Reputation: 119

Is returning an object by reference from a c++-function exception safe?

Is returning an object by (constant) reference from a c++-function generally exception safe - no matter which kind of object (e.g. class object with throwing copy-ctor) is returned? Two example cases:

Example1:

const T& f(const T& parm) {exception_safe_code; return parm;}

Example2:

template <typename T> struct X{ T t; T& get(){return t;} };

Upvotes: 3

Views: 118

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

Assuming that you're returning a reference to an object that will still be alive outside of the function scope, and that the function doesn't have any potentially-throwing code before the return, then... yes, returning a reference cannot ever throw an exception.

struct Foo
{
    std::string x;
    const auto& get_x() noexcept { return x; }
//                      ^^^^^^^^
//                      Safe and recommended.
};

You added some examples - both f and get are exception-safe and can be marked as noexcept.

Upvotes: 3

Related Questions