Search code examples
c++language-lawyer

Can & (address-of-operator) ever return nullptr?


Sounds like a trivial question judging from typical usage of & operator, but is there a guarantee from the standard that address-of-operator cannot return nullptr when trying to get an address?


Solution

  • There is no guarantee that the operator& can't return nullptr, for instance by overloading this operator.

    Here is a contrived example:

    #include <iostream>
    
    struct foo  { foo* operator& ()  { return nullptr; }  };
    
    int main()
    {
        foo f;
        
        if (&f == nullptr) {  std::cout << "nullptr detected\n";  }
        
        std::cout << "the true address is " << std::addressof(f) << "\n";
    }
    

    Demo