Get address of a non-POD object from within a data

2019-04-16 08:01发布

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条回答
可以哭但决不认输i
2楼-- · 2019-04-16 08:33

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.
查看更多
登录 后发表回答