【发布时间】:2018-09-13 17:09:14
【问题描述】:
我在下面有一个简单的 g++7.3.1 -std=c++14 的 sn-p
#include<functional>
#include<iostream>
using namespace std;
struct S{
int m_i = 2;
auto& get2(){return ref(m_i);}
};
int main(){
S s;
s.get2()=4;
cout<<s.m_i<<endl;
return 0;
}
编译错误如下:
error: cannot bind non-const lvalue reference of type ‘std::reference_wrapper<int>&’ to an rvalue of type ‘std::reference_wrapper<int>’
auto& get2(){return ref(m_i);}
~~~^~~~~
In function ‘int main()’:
error: use of deleted function ‘std::reference_wrapper<_Tp>::reference_wrapper(_Tp&&) [with _Tp = int]’
s.get2()=4;
^
In file included from /usr/include/c++/7/bits/std_function.h:44:0,
from /usr/include/c++/7/functional:58,
from xxx.cpp:1:
/usr/include/c++/7/bits/refwrap.h:338:7: note: declared here
reference_wrapper(_Tp&&) = delete;
^~~~~~~~~~~~~~~~~
我知道,通过删除“ref”包装,程序会被编译。我只是想知道在这里使用“ref”有什么问题?
- 只要我想返回一个引用,为什么在这里添加一个“引用”会导致错误?
- 我不明白为什么 g++ 将其视为“使用已删除函数”,正在删除哪个函数?
【问题讨论】:
-
错误信息有什么不清楚的地方?
-
get2返回一个引用。这是一个问题,因为 1)它将是一个悬空引用(它引用的实例在函数末尾超出范围)和 2)您不能将非const引用绑定到临时对象,例如从ref(m_i);获得的那个。只需按值返回。 -
@FrançoisAndrieux 为什么悬空?
-
您是否正在尝试解决一些真正的问题?你的例子似乎只是为了重现错误,否则我不明白你为什么写这个
-
@Rakete1111 该函数返回对临时
std::reference_wrapper的引用。