Martin Fehrs
Martin Fehrs

Reputation: 1091

Why does g++ warn about returning a reference to a temporary

I have the following code:

constexpr const_reference_t at(size_t p_pos) const
{
    using namespace std;

    return (p_pos > m_size)
        ? throw out_of_range{ string{ "string_view_t::at: pos > size() with pos = " } + to_string(p_pos) }
        : m_begin_ptr[p_pos];
}

While compiling, g++ is telling me:

/home/martin/Projekte/pluto/pluto-lib/stringview.hpp:50: Warnung: returning reference to temporary [-Wreturn-local-addr] : m_begin_ptr[p_pos]; ^ m_begin_ptr is:

const_pointer_t m_begin_ptr = nullptr;

and const_pointer_t is of type const char*

Is this code really incorrect or is it a false warning? If g++ is correct, why is this a temporary then? And finally, how could I avoid this warning.

g++ version is 7.2.0

I minimized the code further:

static const char* greeting = "hallo, world!";

const char& nth(unsigned n)
{
    return true ? throw "" : greeting[n];
}

int main()
{
    return 0;
}

Upvotes: 1

Views: 222

Answers (1)

MBI
MBI

Reputation: 593

When (p_pos > m_size) condition is true, you return object created by throw which according to documentation creates temporary object.

The exception object is a temporary object in unspecified storage that is constructed by the throw expression.

Because the function return type is const char&, which is reference, compiler is trying to cast temporary object to reference, so you get the warning.

You shouldn't try to return result of throw, you just only throw.

I would personally change ternary operator part to:

if (p_pos > m_size) {
    // throw
}
return m_begin_ptr[p_pos];

Upvotes: 1

Related Questions