C++ : const reference to local object

标签 c++

const std::string s1 = "abc";
const std::string & s2 = "abc";

s2的定义合法吗?如果是这样,s1s2 之间有什么区别?

谢谢。

最佳答案

是的,s2 是合法的。 s2 绑定(bind)到临时 std::string - 延长临时生命周期。 s1 不是临时变量,而是命名变量。

参见 12.2/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 to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below.

关于C++ : const reference to local object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5635568/

相关文章:

c++ - 无法正确打印 vector 内容

c++ - 优化网络图创建

c++ - 为什么GCC会说 “a function-definition is not allowed here before ' {' token”?

c++ - 2016 年之前的 Valgrind : Memory still reachable with trivial program using <iostream>

c++ - 使用Armadillo做 `Q.slice(a).col(b)`的更有效方法

c++ - 编译用于高放射性环境的应用程序

c++ - 如何在 Xcode 中引用图像和其他对象以及将它们放置在何处?

c++ - 我可以在 OpenGL (C++) 的缓冲区中混合数据类型吗?

java - 在 linux 中使用 JNI 和 C++ 加载动态库

c++ - Eigen 库 : Take a copy of a templated function parameter