c++ - C++11:如何获取外部类的地址/引用?
问题描述
假设以下类(C++11):
class A
{
int i;
class B
{
void meth()
{
// Get outer address / reference?
};
} b;
};
whereB
将永远是其中的一部分A
,即没有像new B()
.
这意味着b.meth()
将始终使用外部操作A
。
问题:如何从外部b.meth()
(它始终具有相同的偏移量b
并且在编译时已知)?
解决方案
这可能不是最好的解决方案,而且它是非标准的,我相信人们会说这是一个坏主意。所以,万一你只是在网上随机发现的,不要盲目使用。但我不确定是否存在标准解决方案。
它是这样的:
// Example program
#include <iostream>
#include <cstdint>
// This may not be needed if your compiler already has an offsetof macro defined
#ifndef offsetof
#define offsetof(s,m) ((::size_t)&reinterpret_cast<char const volatile&>((((s*)0)->m)))
#endif
class A
{
public:
int i;
class B
{
public:
void meth()
{
// We basically subtract the offset of `b` within `A` from the start of `b`,
// giving us the outer `A`'s `this`.
A* outer = (A*)((std::uintptr_t)this - offsetof(A, b));
std::cout << outer->i;
};
} b;
};
int main()
{
A a;
a.i = 123;
a.b.meth();
return 0;
}
// Output: 123
请注意,如果A
不是标准布局类型,这将失败。
无论如何,我认为您应该考虑一种更好的方法来为您的数据结构建模。我发布的是针对您当前问题的创可贴。
推荐阅读
- gcc - 在 NASM 和 GCC 中提供 incbin 路径作为预定义的宏
- c++ - 如何检查排序算法的空间复杂度?
- python - 如何循环遍历字典以更新并返回它?
- html - 在 html 中使用字体
- amazon-web-services - 是否可以在 cognito 中添加静态用户?
- javascript - 如何为谷歌地图标记设置新坐标?
- kotlin - kotlin协程withTimeout在使用withContext获取非阻塞代码时不取消
- swift - 单击 Google 登录按钮时没有任何反应
- javascript - Lodash - 搜索字符串是否包含以开头的单词
- angular - Angular:使用 HttpClient、Observable 和异步管道加载 http 数据时的工作