在中,当我将一个未命名的A
变量传递给B
的变量时,该变量在行后被破坏。据this answer:了解对象的寿命时间,范围,RAII
临时对象是在充分表达的 最终摧毁他们的 一部分。完整的表达式是一个 表达式,它不是某个其他表达式的子表达式 。通常这个 意味着它结束于
; (or) for if, while, switch etc.)
表示结束 的声明。
我得到它,但类B
怎么能知道它的mamber_a
变量的值,它被破坏后?我知道A
的拷贝是enver被调用的。这怎么可能?
#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