如何避免悬挂参考R值

时间:2018-05-03 03:21:51

标签: c++ c++11 rvalue-reference

一些讨论警告悬挂参考,使用R值参考。我在以下示例中没有看到任何悬空引用,因为当main()终止时调用了DTOR。我错过了什么吗?

class test_ctor
{
public:
explicit
test_ctor(int x = 1):_x(x)
{
    std::cout << "CTOR: " << _x << "\n";
}

~test_ctor()
{
    std::cout << "DTOR: " << _x << "\n";
}

test_ctor(test_ctor const & y) = default;

test_ctor(test_ctor && y) = default;
int _x;
};

test_ctor test_rvalue()
{
test_ctor test = test_ctor(2);
return test;
}

现在我可以用两种方式使用上面的代码:

int main(int argc, const char * argv[]) {
auto test = test_rvalue();
std::cout << " test: " << test._x << " \n";
return 0;
}

或者

int main(int argc, const char * argv[]) {
auto && test = test_rvalue();
std::cout << " test: " << test._x << " \n";
return 0;
}

两种情况都有相同的输出:

  

CTOR:2

     

测试:2

     

DTOR:2

这意味着两者都是返回对象的有效方式。 r值参考中是否有任何副作用?

1 个答案:

答案 0 :(得分:2)

中:

"Hello"auto test = test_rvalue();的返回值移至test_rvalue()。然后,每个非脑损坏的编译器都会将此移动 ,因此它永远不会发生。移动构造函数仍然需要存在,但永远不会被调用,并且不会发生移动的任何副作用。

test绑定对auto&& test = test_rvalue();返回的临时值的右值引用。临时生命周期延长以匹配参考的生命周期。

中:

test_rvalue() auto test = test_rvalue();的prvalue返回值用于直接构造变量test_rvalue()。没有移动,不管是否移动。

test案例与保持不变。

相关问题