When to use addressof(x) instead of &x?

前端 未结 5 492
清歌不尽
清歌不尽 2020-12-24 04:53

How do I decide whether I need addressof(x) instead of &x when taking the address of an object?


Seems like the question was confu

5条回答
  •  粉色の甜心
    2020-12-24 05:12

    If it's a user-defined type with overloaded unary operator&, and you want its address, use addressof.

    I'd say you should always use & because, as you say, if you don't, it defeats the purpose of the overload. Unless of course you do something meaningful with the overload, in which case you'd need addressof (outside the class, inside you can just use this), but you have to be very certain of what you're doing.

    Here's more - if you want to overload operator& outside the class (you can), you have to use addressof to return the address, otherwise it results in infinite recursion:

    struct Class
    {
       virtual ~Class() {}
       int x;
    };
    
    void* operator&(const Class& x)
    {
        //return &x; <---- infinite recursion
        return addressof(x) + 4; //I know this isn't safe
                                 //but I also know the intrinsics of my compiler
                                 //and platform to know this will actually return
                                 //the address to the first data member
    }
    

    I know this isn't safe.

提交回复
热议问题