Can one access private member functions through casting to layout-compatible types?

落爺英雄遲暮 提交于 2019-12-04 06:21:33

Yes, you could create a type that uses the same layout as the type you're trying to pilfer from, then reinterpret_cast from that type to your layout compatible type. But this is only protected by the standard if both the source and destination types are standard layout types (and of course, it only actually works if their layouts are the same). So if the source has virtual functions, you're screwed.

This seems to satisfy both of Sutter's issues here. The rules of standard layout ensure that two types that are both standard layout that define the same members in the same order are layout-compatible (section 9.2, paragraph 17):

Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types (3.9).

And the rules for reinterpret_cast specify the meaning of the conversion between two standard layout types (section 5.2.10, paragraph 7):

An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”, the result is static_cast<cv T2*>(static_cast<cv void*>(v)) if both T1 and T2 are standard-layout types (3.9) and the alignment requirements of T2 are no stricter than those of T1, or if either type is void.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!