从数据成员中获取非POD对象的地址,该数据成员是一次性使用的嵌套类 [英] Get address of a non-POD object from within a data member, which is a single-use nested class
问题描述
我将从一些代码开始:
class myNonPODClass
{
public:
virtual ~myNonPODClass() {}
class
{
public:
myNonPODClass* GetContainer()
{
return (myNonPODClass*)((int8_t*)(this) - offsetof(myNonPODClass, member));
}
} member;
};
很明显,这是一个假设的例子。代码编译良好,但我担心非POD类型的偏移量myNonPODClass'。有没有更好的方法来做基本上相同的事情,而不必将myNonPODClass指针传递到嵌套的匿名类构造函数(或类似)? 成员必须准备好没有任何初始化。是否可以?谢谢!
Obviously, this is a contrived example. The code compiles fine, but I'm worried about the "Offset of on non-POD type 'myNonPODClass'". Is there a better way to do essentially the same thing WITHOUT having to pass the myNonPODClass pointer into the nested anonymous classes constructor (or similar)? "member" must be ready to go without any initialization. Is it possible? Thanks!
如果你想知道地球上我可能想要的是什么,我的PROPERTY宏和一个注释掉pastebin的例子(是的,真棒^^) : http://pastebin.com/xnknf39m
In case you're wondering what on Earth I could want this for, my PROPERTY macro and a commented out example on pastebin (yes, it's awesome ^^ ): http://pastebin.com/xnknf39m
推荐答案
根据C ++规范,此代码不起作用,原因如下:
This code does not work, per the C++ specification, for several reasons:
-
offsetof
需要POD类型(在C ++ 11中,它需要一个标准布局类型)。您的类型不是,因此调用它会导致未定义的行为。 - 转换为
int8_t *
每个C ++规范的行为。您需要使用一个char *
,它具有一定的放松规则。
offsetof
requires a POD type (in C++11, it requires a standard-layout type). Your type is not, and therefore calling it results in undefined behavior.- The conversion to
int8_t*
and then to another type is undefined behavior per the C++ specification. You would need to use achar*
, which has certain relaxed casting rules.
这篇关于从数据成员中获取非POD对象的地址,该数据成员是一次性使用的嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!