class 不同 "this"

different "this" at class

我玩了 class 发现了这个好奇心

#include <iostream>
#include <Windows.h>

class pint {
public:
    pint() { std::cout << "ctor >> " << this << std::endl; };
    ~pint() { std::cout << "dtor >> " << this << std::endl; };
    pint(int x) { std::cout << "set 1. >> " << this << std::endl; };
    pint& operator = (const pint& a) { std::cout << "set 2. >> " << this << " | a >> " << &a << std::endl; return *this; };
};

int main()
{
    pint * x1 = new pint;
    *x1 = 8;
    *x1 = 9;

    std::cout << "---------------------" << std::endl;

    pint * x2 = new pint;
    *x2 = 8;
    *x2 = 9;

    std::cout << "---------------------" << std::endl;

    delete x1;
    delete x2;

    while (!GetAsyncKeyState(VK_RETURN))
        Sleep(1);

    return 0;
}

输出:

ctor >> 008731E8
set 1. >> 005BF9A7
set 2. >> 008731E8 | a >> 005BF9A7
dtor >> 005BF9A7
set 1. >> 005BF9A7
set 2. >> 008731E8 | a >> 005BF9A7
dtor >> 005BF9A7
---------------------
ctor >> 00873288
set 1. >> 005BF9A7
set 2. >> 00873288 | a >> 005BF9A7
dtor >> 005BF9A7
set 1. >> 005BF9A6
set 2. >> 00873288 | a >> 005BF9A6
dtor >> 005BF9A6
---------------------
dtor >> 008731E8
dtor >> 00873288

为什么:

这里有趣的是,您不仅拥有一个object!你生成一些临时的。

*x1 = 8;

class 引脚没有 operator=(int),但它可以通过 int 生成 pint object。所以调用了构造函数pint(int)。现在可以将具有新地址的新 object 提供给 operator(const pint&)

这就是您看到 "set1" 文本的原因。 “8”首先会创建一个临时的pintobject,它有一个新的地址。

如果您添加:

,"magic" 将消失
pint& operator = (const int a) { std::cout << "set 3. >> " << this << " | a >> " << &a << std::endl; return *this; };

另一种查看编译器生成具有构造函数的中间临时值的方法,该构造函数能够执行 "unwanted cast",您可以使转换构造函数 explicit.

使用:

explicit pint(int x){...}

现在你的编译器给你一个错误!