有力访问私人会员

Forcefully access private member

本文关键字:访问      更新时间:2023-10-16

说我正在使用一个不知道自己做得很好的人的开源库。(重要成员没有封装(实际上,这是一个我不允许修改的同事,他也不愿意为我修改。

我如何在不进行诸如重写假班或修改原始课程之类的事情的情况下强行访问私人成员?

我已经尝试了诸如#define private public之类的事情,但是类文件包含一些标准名称空间文件,这将给出汇编错误。

我已经尝试了内存操纵,但这需要成员识别,这将无法正常工作。(请参阅以下(

#define PX_ACCESS_PRIVATE( pObject, _Member ) ( static_cast< std::size_t >( pObject ) + static_cast< std::size_t >( &( ( decltype( pObject )( nullptr ) )->_Member ) ) )

有什么想法?

哦,您可以光荣地打破封装。类型系统具有可以利用该效果的漏洞。模板的显式实例不访问其参数。您可以在那里传递任何东西。所以有一点管道...

template<typename Tag>
struct contraband_ {
    using type = typename Tag::type;
    inline static type ptr;
};
template<typename Tag>
inline auto const contraband = contraband_<Tag>::ptr;
template<typename Tag, typename Tag::type ptr_>
class steal : contraband_<Tag> {
    static inline const char filler = [] {
        steal::contraband_::ptr = ptr_;
        return '';
    }();
};

...您可以通过指向该指针进行间接访问任何私人会员...

class foo {
    int x = 3;
};
struct x_tag { using type = int foo::*; };
template class steal<x_tag, &foo::x>;
int main()
{
    foo f;
    // return f.x; ill-formed! Private!
    return f.*contraband<x_tag>; // Okay!
}

看到它的现场。

一个有趣的练习,但您确实应该与同事一起解决问题,而不是诉诸这一问题。出于自己的危险。