gpt4 book ai didi

c++ - 了解对象、范围、RAII 的生命周期

转载 作者:搜寻专家 更新时间:2023-10-31 00:20:55 31 4
gpt4 key购买 nike

below code ,当我将一个未命名的 A 变量传递给 B 的构造函数时,该变量在该行之后被破坏。根据this answer :

Temporary objects are destroyed at the end of the full expression they're part of. A full expression is an expression that isn't a sub-expression of some other expression. Usually this means it ends at the ; (or ) for if, while, switch etc.)denoting the end of the statement.

我明白了,但是 B 类在析构后如何知道它的 mamber_a 变量的值?我知道 A 的复制构造函数被调用过。这怎么可能?

#include <iostream>
using namespace std;

class A
{
int sign;
A();
const A & operator=(const A &);
public:
A(int x) : sign(x) {
cout << "A ctor : " << sign << endl;
}

void WriteA() const {
cout << sign << endl;
}

~A() {
cout << "A dtor : " << sign << endl;
}

A(const A &) {
cout << "A copied : " << sign << endl;
}
};

class B
{
int sign;
const A & member_a;
public:
B(const A & aa , int ww ) : sign (ww) ,member_a(aa) {
cout << "B ctor : " << sign << endl;
}

void WriteB() const {
cout << "Value of member_a :";
member_a.WriteA();
}

~B() {
cout << "B dtor : " << sign << endl;
}
};

int main() {
A a(10);
B b1(a,1);
b1.WriteB();

B b2(A(20),2);
b2.WriteB();

return 0;
}

输出是:

A ctor : 10
B ctor : 1
Value of member_a :10
A ctor : 20
B ctor : 2
A dtor : 20
Value of member_a :20 // Object A was destructed. Where does this 20 come from?
B dtor : 2
B dtor : 1
A dtor : 10

最佳答案

你遇到了 C++ 的棘手部分之一

member_a 的值为 20 纯属偶然。您遇到的是所谓的未定义行为。

当一个类保留对外部对象的引用时,程序员有责任确保该对象的生命周期比被引用的对象的生命周期更长。在这种情况下,当您调用 member_a.WriteA(); 时,a 对象已经被销毁,因此您正在访问可能不属于您的内存(在这种情况下,它恰好位于附近的位置尚未被覆盖(完全偶然))。

如果您要保留对对象的引用。您可以保留一个 const 引用,但有时最好使参数成为一个普通引用,这样您就不会意外地传递一个临时值(这并不总是有效,因为您可能必须通过引用传递一个 const 对象)。

关于c++ - 了解对象、范围、RAII 的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5364902/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com