c++ - cpp 中此指针的大小

标签 c++ gcc sizeof

我发现这个答案的输出因所使用的 gcc 编译器的版本而异。

#include<iostream>
using namespace std;

class ABC{

  int x;

public:

  void show(){

    cout<<sizeof (this);

    cout<<sizeof (*this);

  }
};

int main(){

  ABC ob;
  ob.show();
  return 0;
}

此代码在 4.9.1 版本中给出了 84 的输出,同样在之前的版本中给出了 44。

谁能给我解释清楚“this”指针背后的概念是什么?

最佳答案

this 指针在 N3337 [class.this] 中定义:

1 In the body of a non-static (9.3) member function, the keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*.

所以 sizeof(this) 没有什么特别的。正如 deviantfan 指出的那样,您很可能正在观察编译 32 位程序与 64 位程序的效果。

带有 -m32 的 GCC 输出 4484 没有。

关于c++ - cpp 中此指针的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27400267/

相关文章:

C++ 字符串数组的动态 vector

c++ - MSVC预编译头: Which files need to #include "stdafx.h"?

c++ - 在 Linux 中寻找将加密文本从 C++ 应用程序写入加密 gpg 文件的正确方法

更改 Emacs 中的默认编译器?

c - 在 malloc 内存上使用 sizeof()

c - 带有 sizeof 的简单 printf 根本不起作用

c++ - iOS:在 Objective-C++ 中定义和使用 C++

c++ - 在 C++03 中的未评估上下文中使用表示非静态数据成员的 id 表达式是否有效

c++ - 单个成员结构的对齐和大小保证

c++ - 链接列表操作,问题检索数据 c++