且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

const引用临时生命期延长

更新时间:2023-11-11 23:01:22


如果你有这样的代码:

Both behaviours are standards conforming. If you have code like this:

T foo()
{
  return T();
}

int main()
{
  const T& x = foo();
}

然后,在概念上,在 foo ,创建一个临时对象。这个临时文件被复制到 foo 的返回值。在 main 中,此副本(也是一个临时对象)绑定到 x

作为 foo 的返回值的副本获得其生命周期延长,而不是作为副本源的临时副本。

Then, conceptually, in foo, a temporary object is created. This temporary is copied to the return-value of foo. In main, this copy (which is also a temporary object) is bound to x.
The copy that is the return-value from foo gets its lifetime extended, but not the temporary that was the source for the copy.

但是,C ++标准明确允许消除冗余临时对象。因此, foo 可以直接在该槽中创建临时文件,而不是创建临时文件并将其复制到插槽中以返回值。

这两个选项

But, the C++ standard explicitly allows redundant temporary objects to be elided. So instead of creating a temporary and copying that over into the slot for return values, foo can directly create the temporary in that slot.
Both options are possible, and the compiler does not even have to document when it uses which option.

C ++标准的相关章节是6.6.3([stmt.return])和12.2([class.temporary])。

The relevant sections of the C++ standard are 6.6.3 ([stmt.return]) and 12.2 ([class.temporary]).