c++中 sizeof 运算符是怎么实现的

zlcs8921 2008-03-05 04:50:50
c++ 中 sizeof 运算符是怎么实现的? 硬件实现的? 软件实现的?
...全文
307 15 打赏 收藏 举报
写回复
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
蓝色歌谣 2008-11-20
  • 打赏
  • 举报
回复
c++ 的sizeof 肯定和C 是不一样的,要比后者复杂得多。
michney 2008-03-05
  • 打赏
  • 举报
回复
根据数据类型长度的定义,编译时期计算出来的
michney 2008-03-05
  • 打赏
  • 举报
回复
和标准C的一样
zlcs8921 2008-03-05
  • 打赏
  • 举报
回复
明天再结贴吧。下班了。编了一天程序,脑袋累了。
aiangela 2008-03-05
  • 打赏
  • 举报
回复
这是MSDN 上面的

sizeof Operator
sizeof expression

The sizeof keyword gives the amount of storage, in bytes, associated with a variable or a type (including aggregate types). This keyword returns a value of type size_t.

The expression is either an identifier or a type-cast expression (a type specifier enclosed in parentheses).

When applied to a structure type or variable, sizeof returns the actual size, which may include padding bytes inserted for alignment. When applied to a statically dimensioned array, sizeof returns the size of the entire array. The sizeof operator cannot return the size of dynamically allocated arrays or external arrays.

For related information, see Operators.

Example

// Example of the sizeof keyword
size_t i = sizeof( int );

struct align_depends {
char c;
int i;
};
size_t size = sizeof(align_depends); // The value of size depends on
// the value set with /Zp or
// #pragma pack

int array[] = { 1, 2, 3, 4, 5 }; // sizeof( array ) is 20
// sizeof( array[0] ) is 4
size_t sizearr = // Count of items in array
sizeof( array ) / sizeof( array[0] );
Oversense 2008-03-05
  • 打赏
  • 举报
回复
编译器编译的时候就算好了,有些是已经知道的,比如long,int,有些结构是需要简单计算下的.
zlcs8921 2008-03-05
  • 打赏
  • 举报
回复
你给的代码好像本末倒置了吧?

#define my_sizeof(L_Value) ( \
(char *)(&L_Value + 1) - (char *)&L_Value \
)
你那是编译器已经实现了,你通过内存地址计算得到的。
可是如果没有定义sizeof,怎么实现L_Value 的开辟空间?
都没法开辟空间,
(char *)(&L_Value + 1) - (char *)&L_Value 根本无从谈起。
我想知道c++的实现机制。

p0303230 2008-03-05
  • 打赏
  • 举报
回复
自己定义
方便
zlcs8921 2008-03-05
  • 打赏
  • 举报
回复
//1楼:谢谢阿,那个参考刚看了一下。 java 中跟c++ 中实现的机制一样么?

//2楼:编译器根据C++标准的相关规定实现的.
怎么实现的?

//4楼:自己定义的??

//5楼:事先算好的?
apopgirl 2008-03-05
  • 打赏
  • 举报
回复
kankan
geochway 2008-03-05
  • 打赏
  • 举报
回复
编译器编译时事先算好的.
p0303230 2008-03-05
  • 打赏
  • 举报
回复
#define my_sizeof(L_Value) ( \
(char *)(&L_Value + 1) - (char *)&L_Value \
)
p0303230 2008-03-05
  • 打赏
  • 举报
回复
oo
taodm 2008-03-05
  • 打赏
  • 举报
回复
编译器根据C++标准的相关规定实现的.
z_kris 2008-03-05
  • 打赏
  • 举报
回复
有个参考链接
楼主可以看看
http://blog.sina.com.cn/s/reader_3d73ab6701000axy.html
相关推荐
发帖
C++ 语言

6.3w+

社区成员

C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
帖子事件
创建了帖子
2008-03-05 04:50
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下