如何在c ++中实现sizeof运算符? [英] How is the sizeof operator implemented in c++?

查看:118
本文介绍了如何在c ++中实现sizeof运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以指点我在C ++中实现sizeof运算符,还有一些关于它的实现的描述。

Can someone point me the to the implementation of sizeof operator in C++ and also some description about its implementation.

sizeof是一个不能重载的运算符。

sizeof is one of the operator that cannot be overloaded.

因此,这意味着我们不能更改其默认行为。

So it means we cannot change its default behavior?

推荐答案

sizeof 在C ++中不是一个真正的运算符。它只是插入一个等于参数大小的常量的特殊语法。 sizeof 不需要或没有任何运行时支持。

sizeof is not a real operator in C++. It is merely special syntax which inserts a constant equal to the size of the argument. sizeof doesn't need or have any runtime support.

想知道如何确定一个类/结构的大小看它的定义?这些规则是 ABI 的一部分,编译器仅仅实现它们。基本上规则包括

do you want to know how to determine the size of a class/structure looking at its definition? The rules for this are part of the ABI, and compilers merely implement them. Basically the rules consist of


  1. 原始类型的大小和对齐定义;

  2. 各种指针的结构,大小和对齐方式;

  3. 用于在结构中打包字段的规则;


  1. size and alignment definitions for primitive types;
  2. structure, size and alignment of the various pointers;
  3. rules for packing fields in structures;
  4. rules about virtual table-related stuff (more esoteric).

然而,ABI是平台,通常是供应商特定的,即x86和(说)IA64,下面 A 的大小将不同,因为IA64不允许未对齐的数据访问。

However, ABIs are platform- and often vendor-specific, i.e. on x86 and (say) IA64 the size of A below will be different because IA64 does not permit unaligned data access.

struct A
{
    char i ;
    int  j ;
} ;

assert (sizeof (A) == 5)  ; // x86, MSVC #pragma pack(1)
assert (sizeof (A) == 8)  ; // x86, MSVC default
assert (sizeof (A) == 16) ; // IA64

这篇关于如何在c ++中实现sizeof运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆