問題描述
我基本上想知道 C++ 如何在內(nèi)存中布置對象.所以,我聽說動態(tài)轉(zhuǎn)換只是用偏移量調(diào)整內(nèi)存中對象的指針;和 reinterpret 類型允許我們用這個指針做任何事情.我真的不明白這一點.細(xì)節(jié)將不勝感激!
I am basically wondering how C++ lays out the object in memory. So, I hear that dynamic casts simply adjust the object's pointer in memory with an offset; and reinterpret kind of allows us to do anything with this pointer. I don't really understand this. Details would be appreciated!
推薦答案
每個類都按照聲明的順序排列其數(shù)據(jù)成員.
允許編譯器在成員之間放置填充以提高訪問效率(但不允許重新排序).
Each class lays out its data members in the order of declaration.
The compiler is allowed to place padding between members to make access efficient (but it is not allowed to re-order).
dynamic_cast<>
的工作原理是編譯器實現(xiàn)細(xì)節(jié),標(biāo)準(zhǔn)中沒有定義.這完全取決于編譯器使用的 ABI.
How dynamic_cast<>
works is a compiler implementation detail and not defined by the standard. It will all depend on the ABI used by the compiler.
reinterpret_cast<>
只需更改對象的類型即可.您唯一可以保證有效的是,將指向 void* 的指針轉(zhuǎn)換為指向 class 的指針將返回相同的指針.
reinterpret_cast<>
works by just changing the type of the object. The only thing that you can guarantee that works is that casting a pointer to a void* and back to the same the pointer to class will give you the same pointer.
這篇關(guān)于內(nèi)存布局 C++ 對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!