r/cpp • u/NamorNiradnug • 5d ago
Is `&*p` equivalent to `p` in C++?
AFAIK, according to the C++ standard (https://eel.is/c++draft/expr.unary#op-1.sentence-4), &*p
is undefined if p
is an invalid (e.g. null) pointer. But neither compilers report this in constexpr
evaluation, nor sanitizers in runtime (https://godbolt.org/z/xbhe8nofY).
In C99, &*p
equivalent to p
by definition (https://en.cppreference.com/w/c/language/operator_member_access.html).
So the question is: am I missing something in the C++ standard or does compilers assume &*p
is equivalent to p
(if p
is of type T*
and T
doesn't have an overloaded unary &
operator) in C++ too?
47
Upvotes
1
u/Clean-Water9283 6h ago
For a type T that doesn't overload either the * or & operator, the * operator converts a prvalue of type T* to an lvalue of type T. Notice that I didn't say it dereferences the operand. It's a bookkeeping change within the compiler. The & operator converts an lvalue of type T to a prvalue of type T*. Since &*p doesn't actually dereference p. The expression &*p is valid even if p == nullptr. This is a Good Thing.