[英]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:编译时,g++ 告诉我:
/home/martin/Projekte/pluto/pluto-lib/stringview.hpp:50: Warnung: returning reference to temporary [-Wreturn-local-addr] : m_begin_ptr[p_pos]; /home/martin/Projekte/pluto/pluto-lib/stringview.hpp:50: 警告:返回对临时 [-Wreturn-local-addr] 的引用:m_begin_ptr[p_pos]; ^ m_begin_ptr is: ^ m_begin_ptr 是:
const_pointer_t m_begin_ptr = nullptr;
and const_pointer_t is of type const char*而 const_pointer_t 的类型是 const char*
Is this code really incorrect or is it a false warning?这段代码是真的不正确还是错误的警告? If g++ is correct, why is this a temporary then?如果 g++ 是正确的,那为什么这是一个临时的呢? And finally, how could I avoid this warning.最后,我怎么能避免这个警告。
g++ version is 7.2.0 g++ 版本是 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;
}
When (p_pos > m_size)
condition is true
, you return object created by throw which according to documentation creates temporary object.当(p_pos > m_size)
条件为true
,返回由throw创建的对象,根据文档创建临时对象。
The exception object is a temporary object in unspecified storage that is constructed by the throw expression.异常对象是由 throw 表达式构造的未指定存储中的临时对象。
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.因为函数返回类型是const char&
,它是引用,编译器试图将临时对象转换为引用,所以你会收到警告。
You shouldn't try to return result of throw
, you just only throw
.你不应该试图返回throw
结果,你只是throw
。
I would personally change ternary operator part to:我个人将三元运算符部分更改为:
if (p_pos > m_size) {
// throw
}
return m_begin_ptr[p_pos];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.