Does forming a reference to an object constitute access?
Here's what GCC and Clang currently do:
void test(int const volatile* ptr) noexcept {
*ptr; // movl (%rdi), eax // Reads *ptr
[[maybe_unused]] int const volatile& ref = *ptr; // Does not read *ptr
}
My question is specifically about the statement
[[maybe_unused]] int const volatile& ref = *ptr;
- According to the abstract machine, does this read the value of the object pointed to by
ptr
? Would this statement, in isolation, be undefined behavior ifptr == nullptr
?- Yes, indirection on null pointer is UB - https://stackoverflow.com/a/59205697/1614051
- Would it be an aliasing violation if
ptr
pointed to something other than anint
?
Note that I ask specifically about forming the reference, and not about using it to read the value.
Edit 09/12/2019: Accepting the following answers:
- Does
int const volatile& ref = *ptr;
read the value of the pointed-to object?- No.
- Is this undefined when
ptr == nullptr
?- Yes,
*ptr
on a null pointer is undefined.
- Yes,
- Is forming the reference an aliasing violation if
ptr
points to an object of different type?- No, just forming the reference does not violate strict aliasing.
- Presumably
reinterpret_cast
-ing the reference to the correct type is allowed and valid.
Thus, the meaning of the expression
*ptr
is only defined for pointerptr
that points to an object or function - that is, a pointer whose value falls under [basic.compound]/(3.1). In all other cases, this expression exhibits undefined behavior.