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

吃可爱长大的小学妹 提交于 2019-12-22 00:43:04

问题


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:


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.


来源:https://stackoverflow.com/questions/11856480/get-address-of-a-non-pod-object-from-within-a-data-member-which-is-a-single-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!