返回临时对象并绑定到 const 引用

2023-12-03C/C++开发问题
16

本文介绍了返回临时对象并绑定到 const 引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

可能的重复:
const 引用是否会延长临时引用的寿命?

我的编译器不会抱怨将临时分配给 const 引用:

My compiler doesn't complain about assigning temporary to const reference:

string foo() {
  return string("123");
};

int main() {
  const string& val = foo();
  printf("%s
", val.c_str());
  return 0;
}

为什么?我认为从 foo 返回的字符串是临时的,val 可以指向生命周期已经结束的对象.C++ 标准是否允许这样做并延长返回对象的生命周期?

Why? I thought that string returned from foo is temporary and val can point to object which lifetime has finished. Does C++ standard allow this and prolongs the lifetime of returned object?

推荐答案

这是一个 C++ 特性.该代码是有效的,并且完全符合它的功能.

This is a C++ feature. The code is valid and does exactly what it appears to do.

通常,临时对象仅持续到它出现的完整表达式的结尾.但是,C++ 特意指定将临时对象绑定到堆栈上对 const 的引用会将临时对象的生命周期延长至引用本身的生命周期,从而避免常见的悬空引用错误.在上面的例子中, foo() 返回的临时值一直存在到右花括号为止.

Normally, a temporary object lasts only until the end of the full expression in which it appears. However, C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error. In the example above, the temporary returned by foo() lives until the closing curly brace.

P.S:这仅适用于基于堆栈的引用.它不适用于作为对象成员的引用.

P.S: This only applies to stack-based references. It doesn’t work for references that are members of objects.

全文:GotW #88:AHerb Sutter 的最重要的常量"候选者.

这篇关于返回临时对象并绑定到 const 引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6