【问题标题】:different "this" at class课堂上不同的“这个”
【发布时间】:2018-04-03 19:17:16
【问题描述】:

我在课堂上玩耍,发现了这种好奇心

#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

为什么:

  • “this”在全班不一样?
  • 输出的第一部分是“设置 1”。同样,在输出的第二部分是“set 1”。不一样?
  • “设置 1”。与ctor不同? (如果是因为制造新物体或类似的东西,为什么要制造它?)
  • “a”等于“设置 1”。并且“ctor”/“dtor”(最后)等于“set 2”。 ?
  • “设置 1”。打电话给 dtor?

【问题讨论】:

  • 可以复制或移动引用。 C++ 不保证对象在其整个生命周期内都应具有相同的地址。
  • @sturcotte06 我不确定我理解你所说的引用可以移动是什么意思。
  • 那为什么在 set 2. 和 dtor 是一样的呢?
  • *x1 = 8; 和朋友们各自创建一个临时的pint 作为operator= 的参数。 operator= 没有使用 int 的重载。
  • @sturcotte06:你写的完全错了!如果一个对象可以移动其地址,则永远不可能使用指向它的引用或指针。非常有趣的是,人们为此投票!在 C++ 中,一个对象永远不能移开!!!移动操作意味着通过指向新对象的指针获取内容。那从来没有移动过物体本身!

标签: c++ class this pass-by-reference


【解决方案1】:

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

*x1 = 8;

类 pin 没有operator=(int),但它可以通过 int 生成 pint 对象。所以构造函数pint(int) 被调用。现在可以将具有新地址的新对象提供给operator(const pint&amp;)

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

如果添加,“魔法”就会消失:

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

另一种查看编译器使用能够执行“不需要的强制转换”的构造函数生成中间临时变量的方法,您可以将转换构造函数设为explicit

使用:

explicit pint(int x){...}

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

【讨论】:

    猜你喜欢
    • 2019-10-28
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多