有力访问私人会员
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!
}
看到它的现场。
一个有趣的练习,但您确实应该与同事一起解决问题,而不是诉诸这一问题。出于自己的危险。
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- 尝试通过多个向量访问变量时,向量下标超出范围
- 无法访问嵌套类.类的使用无效
- 写入位置0x0000000C时发生访问冲突
- 我们可以访问一个不存在的联盟的成员吗
- C++从另一个类访问公共静态向量的正确方法是什么
- 我的简单if-else语句是如何无法访问的代码
- 从C++dll访问C#中的一行主要参数
- 概念TS检查忽略私有访问修饰符
- 访问被拒绝后,c++中的故障保护代码
- 在c++中访问int到类对象的映射时出错
- 我想访问std::unique_ptr中的一个特定元素
- 为什么示例代码访问IUnknown中已删除的内存
- C++:无法访问声明的受保护成员
- 通过指向指针数组的指针访问子类的属性
- 如何使用单独文件中的派生类访问友元函数对象