Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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;} };
like image 741
Teilhart Avatar asked Apr 20 '26 04:04

Teilhart


1 Answers

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.

like image 108
Vittorio Romeo Avatar answered Apr 22 '26 16:04

Vittorio Romeo