C++指向临时变量的引用
C++ reference pointing to a temporary variable?
class ClassB {
int m_b;
public:
ClassB(int b) : m_b(b) {}
void PrintClassB() const {
cout << "m_b: " << m_b << endl;
}
};
int main(int argc, char* argv[])
{
const ClassB &af = ClassB(1);
af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3
}
鉴于上面的代码,我很难理解这个片段:
Q1>这句话是什么意思?
const ClassB &af = ClassB(1);
以下是我的理解:
af refers to a temporary variable ClassB(1) and after the
执行此行,临时变量被销毁并 af 指未定义的变量。在此过程中,没有 调用复制构造函数。
那为什么我们还能发出以下声明并得到结果呢?
af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3
const ClassB &af = ClassB(1);
const
这里延长了正在创建的临时对象(即ClassB(1)
(的生命周期。它的范围一直持续到af
超出范围;
af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3
这是因为,af
只不过是临时对象的引用,该引用是构造的,1
传递给它的构造函数。
您所看到的是由标准保证的。
C++03 12.2 临时对象:
第二个上下文是当引用绑定到临时时。引用绑定到的临时或作为临时绑定的子对象的完整对象的临时在引用的生存期内持续存在,除非下面指定...
[示例:
class C {
// ...
public:
C();
C(int);
friend C operator+(const C&, const C&);
˜C();
};
C obj1;
const C& cr = C(16)+C(23);
C obj2;
..a third temporary T3 to hold the result of the addition of these two expressions.
The temporary T3 is then bound to the reference cr..The temporary T3 bound to the
reference cr is destroyed at the end of cr’s lifetime, that is, at the end of the
program.
—结束示例]
我认为你可以依靠Herb Sutter博客中的这个例子来帮助你理解参考文献,常量参考文献及其生命周期。http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/(
来自他的博客:
通常,临时对象仅持续到它出现的完整表达式的末尾。但是,C++特意指定将临时对象绑定到堆栈上的 const 引用可将临时对象的生存期延长到引用本身的生存期,从而避免了常见的悬空引用错误
不,你误解了行为,这是一个定义明确的行为。
临时绑定到 const引用的生存期一直持续到 const 的生存期。
因此,从ClassB(1)
临时返回的寿命因此延长到af
的生命周期,即main
的闭合支撑。
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 多个"常量引用"变量可以共享同一个内存吗?
- 如果非动态变量被指针引用,何时超出范围?
- 在 c++ 中将变量作为结构构造函数中的引用传递
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- 为什么C++可以使用未初始化的成员变量(引用或指针 *NOT 值复制*)来初始化其父类的成员变量
- 地址运算符是否返回变量引用的对象的地址
- 未在另一个函数中设置变量引用的问题
- 英特尔样式内联程序集和 AT&T 样式中的变量引用,C++
- 将成员变量引用为类成员
- 从静态变量引用非静态变量会使非静态变量先于静态变量进行析构函数
- 何时解析 C++11 lambda 表达式中的变量引用
- 堆栈/堆变量的变量/引用名称或类型存储在内存中的位置
- C++强制对变量引用进行编译优化,使之成为直接的
- Boost变量引用和相等比较
- 使复制的成员引用变量引用副本的成员,而不是原始成员的成员
- 为什么要在Java中生成变量引用数组
- 捕获和调试对移动lambda内部局部变量引用的无效使用
- 在变量初始化后更改变量引用
- 从'C'程序中提取变量定义和变量引用