I'll start with some code:
class myNonPODClass
{
public:
virtual ~myNonPODClass() {}
class
{
public:
myNonPODClass* GetContainer()
{
return (myNonPODClass*)((int8_t*)(this) - offsetof(myNonPODClass, member));
}
} member;
};
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!
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
This code does not work, per the C++ specification, for several reasons:
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.
来源:https://stackoverflow.com/questions/11856480/get-address-of-a-non-pod-object-from-within-a-data-member-which-is-a-single-use