为什么g ++会警告返回对临时引用的引用

时间:2017-10-06 13:56:56

标签: c++ g++ warnings

我有以下代码:

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];
}

编译时,g ++告诉我:

/home/martin/Projekte/pluto/pluto-lib/stringview.hpp:50:Warnung:返回对临时[-Wreturn-local-addr]的引用              :m_begin_ptr [p_pos];                                 ^ m_begin_ptr是:

const_pointer_t m_begin_ptr = nullptr;

和const_pointer_t的类型为const char *

此代码是否真的不正确或是否为虚假警告?如果g ++是正确的,为什么这是暂时的呢?最后,我怎么能避免这个警告。

g ++版本是7.2.0

我进一步减少了代码:

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

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

int main()
{
    return 0;
}

1 个答案:

答案 0 :(得分:1)

(p_pos > m_size)条件为true时,您返回由throw创建的对象,根据文档创建临时对象。

  

异常对象是未指定存储中的临时对象,由throw表达式构建。

因为函数返回类型是const char&,这是引用,编译器正在尝试将临时对象转换为引用,因此您会收到警告。

您不应该尝试返回throw的结果,而只是throw

我个人会将三元运算符部分更改为:

if (p_pos > m_size) {
    // throw
}
return m_begin_ptr[p_pos];
相关问题