[英]Get outer object pointer inside inner object
There are two objects: Holder
and Property
.有两个对象:
Holder
和Property
。 Holder
contains Property
as a field. Holder
包含Property
作为字段。 I want to get access to Holder
from Property
.我想从
Property
访问Holder
。 In general case the address of Property
will be address of Holder
+ offset of field of type Property
.在一般情况下,
Property
的地址将是Holder
的地址 + Property
类型字段的偏移量。
But important : the Property
should not have any fields (for example I can't pass the Holder
to constructor of Property
and save it as 'outer').但重要的是:
Property
不应该有任何字段(例如,我不能将Holder
传递给Property
的构造函数并将其保存为“外部”)。
UPD: I suppose this trick should only work for the standard layout. UPD:我想这个技巧只适用于标准布局。
UPD2: The main reason why I want to use such approach (do not pass reference to Property
) is use minimum memory as possible in Holder
object. UPD2:我想使用这种方法(不传递对
Property
的引用)的主要原因是在Holder
对象中使用尽可能少的内存。 In best case: sizeof(Property)
is 0 bytes (Although the standard does not allow this).在最好的情况下:
sizeof(Property)
为 0 字节(尽管标准不允许这样做)。
First that I tried to do is pass pointer to member to template parameter:首先,我尝试做的是将指向成员的指针传递给模板参数:
Property<&Holder::prop> prop;
or要么
Property<offsetof(Holder, prop)> prop;
But prop
is not defined yet (it is error).但是
prop
还没有定义(这是错误的)。
Full pseudocode will looks like this:完整的伪代码如下所示:
template<size_t FieldOffset>
class Property
{
class Holder* GetOuter()
{
return (char*)this - FieldOffset; // go to Outer object via offset of our field
}
}
class Holder
{
int Field1;
std::string Field2;
Property<offsetof(Holder, prop)> prop; // Error!
}
Are there any other suggestions to do something similar?还有其他建议可以做类似的事情吗?
The memory model in C++ allows navigation from a member subobject to its containing (class-type) object only when the class is standard-layout and the member is the first member.只有当类是标准布局且成员是第一个成员时,C++ 中的内存模型才允许从成员子对象导航到它的包含(类类型)对象。 The idea is that compilers can reason about which pointers have to escape for a write to necessitate reloading some other value from memory.
这个想法是,编译器可以推断哪些指针必须转义才能进行写入,从而需要从内存中重新加载一些其他值。 As such, what you want is impossible in almost all cases, although there have been proposals to relax that rule so as to add features like this one.
因此,几乎在所有情况下你想要的都是不可能的,尽管有人提议放宽该规则以添加类似这样的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.