Search code examples
c++c++11memory-addresslvaluervalue

Is there exception to rule that if address can be find out using & it's lvalue?


Is there any exception to rule that if I can find address using & it's l-value otherwise r-value?

For example,

int i;

&i will give address of i, but I cannot take address of (i + 5), unless I is pointer or array.

Regards


Solution

  • The most obvious exception is overloading the prefix & operator for your own type:

    #include <iostream>
    
    struct X
    {
        X* operator&()
        {
            return this;
        }
    };
    
    int main()
    {
        std::cout << &X() << '\n';
    }
    

    This prints the address of the temporary object, which happens to be 0x7fff76012d9f when I ran it.