- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
在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/
我正在开发一个使用多个 turtle 的滚动游戏。玩家 turtle 根据按键命令在 Y 轴上移动。当危害和好处在 X 轴上移动时,然后循环并改变 Y 轴位置。我尝试定义一个名为 colliding(
我不明白为什么他们不接受这个作为解决方案,他们说这是一个错误的答案:- #include int main(void) { int val=0; printf("Input:- \n
我正在使用基于表单的身份验证。 我有一个注销链接,如下所示: 以及对应的注销方法: public String logout() { FacesContext.getCurren
在 IIS7 应用程序池中有一个设置 Idle-time out 默认是 20 分钟,其中说: Amount of time(in minutes) a worker process will rem
我是一名优秀的程序员,十分优秀!