为什么在C ++中,分配的对象的地址不变?

TMOTTM

在此C ++示例中,类C具有默认构造函数,副本构造函数和赋值运算符:

struct C {
    C();
    C(const C& c);
    C& operator=(const C& c);
};

该实现如下,带有一些用于跟踪对象的输出。我在命令行的注释中添加了一些示例地址,作为对以下main程序的引用

#include "C.h"
#include <iostream>
using namespace std;

C::C() {
    cout << "Standard constructor." << endl;
}

C::C(const C& c) {
    cout << "Copy constructor." << endl;
}

C& C::operator=(const C& c) {
    cout << "Address of reference argument: &c = " << &c << endl;      // F9B4
    cout << "Address of this: &*this =           " << &*this << endl;  // F8D4
    return *this;
}

我将使用一种返回匿名对象的工厂方法:

C foo() {
    return C();
}

现在,在下面的程序中,我创建一个命名对象c(请参阅(1))并创建一个匿名对象(2),并将其分配给c(3)。我希望c分配后具有匿名对象的地址。

int main()
{
    C c;  // (1)
    cout << "Address of initial c from main: &c = " << &c << endl;                  // F8D4
    c=foo();  // (2) and (3)
    cout << "Address of initial c from main after assignment: &c = " << &c << endl; // Expected F9B4 but is F8D4
}
黑猫

C ++中的对象永远不会更改地址。

赋值运算符与任何其他方法都没有什么不同,通常它只是遍历所有成员变量并为它们分配新值,这些值是从另一个对象的相应成员中复制的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章