为什么 g++ 警告返回对临时的引用
Why does g++ warn about returning a reference to a temporary
我有以下代码:
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;
}
当条件true
(p_pos > m_size)
时,你返回由throw创建的对象,根据文档创建临时对象。
异常对象是由 throw 表达式构造的未指定存储中的临时对象。
由于函数返回类型为 const char&
,即引用,因此编译器正在尝试将临时对象强制转换为引用,因此您会收到警告。
你不应该尝试返回throw
的结果,你只是throw
。
我个人会将三元运算符部分更改为:
if (p_pos > m_size) {
// throw
}
return m_begin_ptr[p_pos];
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?