有人可以幫助我理解爲什麼下面的代碼將導致警告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