template <class T> T* addressof (T& ref) noexcept;
Address of object or function
Returns the address of the object or function referenced by ref.
This function returns the address of ref even in the presence of an overloaded reference operator (operator&).
// addressof example
#include <iostream>
#include <memory>
struct unreferenceable {
int x;
unreferenceable* operator&() { return nullptr; }
};
void print (unreferenceable* m) {
if (m) std::cout << m->x << '\n';
else std::cout << "[null pointer]\n";
}
int main () {
void(*pfn)(unreferenceable*) = std::addressof(print);
unreferenceable val {10};
unreferenceable* foo = &val;
unreferenceable* bar = std::addressof(val);
unreferenceable* tee = reinterpret_cast<unreferenceable*>(&(val.x));
std::cout << &val << std::endl;
std::cout << foo << std::endl;
std::cout << bar << std::endl;
std::cout << tee << std::endl;
(*pfn)(foo); // prints [null pointer]
(*pfn)(bar); // prints 10
(*pfn)(tee); // prints 10
return 0;
}
输出结果为:
:g++ -std=c++11 -O0 main.cc -o main
:./main
0x0
0x0
0x7ffee3806988
0x7ffee3806988
[null pointer]
10
10
注意类型重载:
unreferenceable* operator&() { return nullptr; }