According to the C++23 standard, what is the output of this program?
#include <iostream>
#include <memory>
struct S {
S(int i) : i_(i){}
S* operator&() const;
int i_;
};
S global{1};
S* S::operator&() const { return &global; }
int main() {
S s(2);
S* ptr = std::addressof(s);
std::cout << ptr->i_;
}Do std::addressof(s) and &s mean the same thing?
2
S::operator& has been overloaded to return the address of the global S global, rather than the address of whichever S object the caller calls it on. This would cause infinite recursion, since the implementation does &global which would call the same S::operator& again.
The question then is whether std::addressof calls S::operator& at all.
§[specialized.addressof]¶1 in the standard has the answer:
template <class T> constexpr T* addressof(T& r) noexcept;Returns: The actual address of the object or function referenced by
r, even in the presence of an overloadedoperator&.
So addressof ignores the overloaded operator&, and this is indeed its purpose. It computes the actual address of s, and we can then print its member i_ which holds the value 2.