function template
<memory>
std::addressof
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&).
Parameters
- ref
- An object or function.
Return value
A pointer to the object or function.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
// 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);
(*pfn)(foo); // prints [null pointer]
(*pfn)(bar); // prints 10
return 0;
}
|
Output: