有人可以帮助我理解为什么下面的代码将导致警告R值将导致警告,而不使用std ::的移动
struct A
{
A() : _a(0) {}
const int& _a;
};
int main()
{
A a;
}
与警告
warning: binding reference member '_a' to a temporary value [-Wdangling-field]
A() : _a(0) {}
但是这个代码,其中std::move
用于初始化成员_a
,并不:
struct A
{
A() : _a(std::move(0)) {}
const int& _a;
};
int main()
{
A a;
}
是不是0
和std::move(0)
这两个r值?
_a在哪里指这里? – Steephen
'_a'是一个引用,在ex1中你将它绑定到一个临时('0'),以后使用它是UB。在ex2中,你使用'std :: move'作为转换来对编译器进行“撒谎”,它会使警告静音,但稍后访问它仍然是UB。 –
'const&'在类中使用时不延长生命周期。它只适用于函数参数和函数返回。 – NathanOliver