c++ - 将右值分配给 'const auto&' 时会发生什么

标签 c++ c++11 reference lvalue rvalue

在这种情况下会发生什么?

// assume WeakPtr is valid and has not expired
const auto& something = WeakPtr.lock();
something->doStuff();

这是未定义的吗?

在这种情况下它会改变吗?

std::shared_ptr<Something> getSomething() { return mSomething.lock(); }
const auto& something = getSomething();

那这个呢?

std::vector<int> getInts() { return std::vector<int>{ 1, 2, 3 }; }
const auto& ints = getInts();

在每一种情况下,const auto& 都暗示我想绑定(bind)一个对象的引用,但在每一种情况下,我都将它绑定(bind)到一个临时的右值对象。我是在招来灾难吗?

最佳答案

Is this undefined?

每个案例都有明确的定义。

What happens in this case?

在每种情况下,临时对象的生命周期都会延长,以匹配标准 [class.temporary] 部分中描述的 const 引用的生命周期。

[class.temporary] (standard draft)

4 There are two contexts in which temporaries are destroyed at a different point than the end of the full- expression. The first context is ... [irrelevant to your cases]

5 The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except ... [a few exceptions which do not apply to your cases]

关于c++ - 将右值分配给 'const auto&' 时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42868744/

相关文章:

c++ - 使用reverse_iterator STL错误解密upper_bound

c++ - 如何从 Visual Studio C++ 项目使用 RTMPDump?

c++ - 如何修复条件变量等待/通知的竞争条件

c++ - 在自定义容器中调用析构函数

用于复杂类型的单一方法的 C++ 模板特化

c - 为什么不能在函数中修改结构体的成员变量?

c++ - 如何在 C++ 中创建临时变量

c# - 如何通过引用传递 System.Action?

c++ - 对已经有效的指针使用 new

c++ - `class template Example<int>;` 语句对 C++11 意味着什么?