下面的程序使用gcc編譯並在32位架構上執行時會返回16個字節。我想知道爲什麼它會返回,因爲它既沒有使用長雙成員,也沒有在64位機器上運行,也沒有定義虛函數來獲取額外的內存字節,並且在計算double時的大小以及int數據成員,結果大約有12個字節。那麼爲什麼這16個字節值?爲什麼這個C++程序返回16個字節?
class A {
public:
void* data;
};
void* operator new (size_t sz, A& obj) {
printf("Custom operator new called for %d bytes\n", sz);
return obj.data;
}
class foo {
public:
double a;
int x;
foo() { printf("foo constructor called (this=%p)\n", this); }
};
int main() {
A obj;
obj.data = malloc(sizeof(foo));
printf("Allocator data: %p\n", obj.data); // Allocator data: 0x4601a8
foo *f = new (obj) foo; // Custom operator new called for **16 bytes**
// foo constructor called (this=0x4601a8)
printf("foo allocated at %p\n", f); // foo allocated at 0x4601a8
}
結構物體內可能存在無名填充 – michaeltang
取決於您的默認填充 - 1,2或4個字節的填充,您將得到12.使用8或16字節填充,您將得到16. – cup