Is it safe to cast to a class that has the same data member layout, but a different implementation?

后端 未结 2 1741
暖寄归人
暖寄归人 2021-02-14 18:53

The first class will be used for private inheritance in order to ensure the exact same layout. This should make casting safe.

#include 
#include          


        
2条回答
  •  死守一世寂寞
    2021-02-14 19:49

    It's more or less what's described here, the so called boost mutant idiom.

    There it is said that (emphasis mine):

    Boost mutant idiom makes use of reinterpret_cast and depends heavily on assumption that the memory layouts of two different structures with identical data members (types and order) are interchangeable. Although the C++ standard does not guarantee this property, virtually all the compilers satisfy it. Moreover, the mutant idiom is standard if only POD types are used.


    Note: that page is pretty outdated, I don't know if the most recent revisions changed something about the guarantees above mentioned.

提交回复
热议问题