将右值分配给 'const auto&' 时会发生什么
What happens when assigning an rvalue to 'const auto&'
在这种情况下会发生什么?
// 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&
都暗示我想绑定对象的引用,但在每一种情况下,我都将其绑定到临时右值对象。我是在招祸吗?
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]
在这种情况下会发生什么?
// 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&
都暗示我想绑定对象的引用,但在每一种情况下,我都将其绑定到临时右值对象。我是在招祸吗?
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]