Get address of a non-POD object from within a data member, which is a single-use nested class

235 views Asked by At

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

1

There are 1 answers

0
Nicol Bolas On

This code does not work, per the C++ specification, for several reasons:

  1. 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.
  2. The conversion to int8_t* and then to another type is undefined behavior per the C++ specification. You would need to use a char*, which has certain relaxed casting rules.