Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

指標(Pointer)所佔的記憶體大小...?

0 views
Skip to first unread message

嵐雲

unread,
Dec 17, 1996, 3:00:00 AM12/17/96
to

我一直以為,
不管是什麼類型的指標, 它所佔的記憶體大小都是一樣的,
因為, 實際上它的值只是一個位址, 而在 32bit 定址的系統
裏, 都是佔 4 個 byte.

今天發現, 有例外,
在一台 SunOS 4.x 裏, 使用 gcc,
一個 function pointer 佔了4Byte,
一個 class 的 method pointer 卻佔了 8Byte.
在 NT 下用 VC++ 4.2,
則二者皆為 4byte,

這是因為什麼緣故呢?
cpu? os? compiler?
那多出來的 4 byte 是存什麼? 為了最佳化?
ps.
結果:
SunOS...
function pointer size 'sizeof((void)(*)())' is 4
method pointer size 'sizeof((void)(classx::*)())' is 8
NT ...
function pointer size 'sizeof((void)(*)())' is 4
method pointer size 'sizeof((void)(classx::*)())' is 4
底下是程式,
有興趣的人可以試試不同狀況組合的結果....

#include <stdio.h>

struct classx
{
};

void main()
{
printf(" function pointer size 'sizeof((void)(*)())' is %d \n",sizeof(vo
printf(" method pointer size 'sizeof((void)(classx::*)())' is %d \n", si

}


--
歡迎至 http://gais.cs.ccu.edu.tw/ 使用 GAIS 查詢台灣學術網路資源(BBS,WWW,FTP)
EightCloud(嵐雲)

四眼的王蟲

unread,
Dec 17, 1996, 3:00:00 AM12/17/96
to

EightCloud.bbs@firebird (嵐雲) wrote:

>
>我一直以為,
> 不管是什麼類型的指標, 它所佔的記憶體大小都是一樣的,
> 因為, 實際上它的值只是一個位址, 而在 32bit 定址的系統
> 裏, 都是佔 4 個 byte.
>
>今天發現, 有例外,
> 在一台 SunOS 4.x 裏, 使用 gcc,
> 一個 function pointer 佔了4Byte,
> 一個 class 的 method pointer 卻佔了 8Byte.
> 在 NT 下用 VC++ 4.2,
> 則二者皆為 4byte,
>
>這是因為什麼緣故呢?
> cpu? os? compiler?
> 那多出來的 4 byte 是存什麼? 為了最佳化?

我並不清楚為何在 SunOS 裡的 gcc 其 class 的 method pointer 為
8 byte, 這應該是 compiler 的 implement 方式而與 cpu, os 無關,
pointers to member functions 並不一定是 member function 的 machine
address, C++ FAQ Q122 有一段說:

NOTE: do NOT attempt to "cast" a ptr-to-mem-fn into a ptr-to-fn;
the result is undefined and probably disastrous. E.g., a ptr-to-
member-fn is NOT required to contain the machine addr of the
appropriate fn (see ARM, 8.1.2c, p.158).

另外 The Designe and Evolution of C++ p.303 說:

The term pointer to member is a bit misleading because a pointer to
member is more like an offset, a value that identifies a member of
an object.

由以上我們可以知道 pointer to member funtion 與 function pointer
有很大的不同, pointer to member function 應該也不只是一個隱含
this 指標的 function pointer 而已.

在寫 C/C++ 的程式時不要假設某個 type 佔幾個 byte, 而要用 sizeof,
這又是一個很好的範例.

四眼的王蟲

--
生命是在黑暗中閃爍的光

0 new messages