![](/img/trans.png)
[英]What values are stored in the padding bytes of an aligned struct/class object
[英]Are class/struct functions stored in an object?
假設這個:
struct A {
int a;
int b;
};
struct B {
int a;
int b;
int func() {
return this->a + this->b;
}
};
B
的實例是否包含指向func
的指針?
在代碼中說明這個問題:
A a; // first 4 bytes are for `int a`, second 4 bytes are for `int b`
B b: // ditto, but is there an extra word for a pointer to function `func`?
號這兩個a
和b
是完全一樣的尺寸( b
不存儲一個指針func
)。
C ++中的類函數沒有與對象本身鏈接(指向),它們只是作為任何其他函數存儲。 當你調用一個類函數時,你只是調用一個普通函數(你不是從指針調用它)。 這就是做b.func = another_func;
在C ++中是非法的。
為了在代碼中說明這一點:
/////////
// C++
/////////
struct B {
int a;
int b;
int func() {
return this->a + this->b;
}
};
B b;
b.func();
//////////////////////////////
// Example compile output if it was compiled to C (not actual compile output!)
// i.e. this C code will do the equivalent of the C++ code above
//////////////////////////////
struct B {
int a;
int b;
};
int B_func(struct B* this) {
return this->a + this->b;
}
B b;
B_func(&b);
// This should illustrate why it is impossible to do this in C++:
// b.func = another_func;
C ++函數實際上只是(可能)將對象的隱藏指針作為第一個參數的函數。 通過名稱修改實現唯一性。
除非功能是虛擬的; 具有一個或多個虛函數的類具有“虛函數表”(vtable),並且這些類的實例具有指向其特定於實例的vtable的指針的開銷。 vtable是在對象之前還是之后取決於編譯器/實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.