How can I reliably get an object's address when operator& is overloaded?

前端 未结 5 1376
野性不改
野性不改 2020-11-27 09:55

Consider the following program:

struct ghost
{
    // ghosts like to pretend that they don\'t exist
    ghost* operator&() const volatile { return 0; }
}         


        
5条回答
  •  盖世英雄少女心
    2020-11-27 10:33

    Use std::addressof.

    You can think of it as doing the following behind the scenes:

    1. Reinterpret the object as a reference-to-char
    2. Take the address of that (won’t call the overload)
    3. Cast the pointer back to a pointer of your type.

    Existing implementations (including Boost.Addressof) do exactly that, just taking additional care of const and volatile qualification.

提交回复
热议问题