Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you dereference a temporary array?

Consider the following code:

void foo() {
    int arr[1];
    *arr; // OK

    using T = int[1];
    *T{}; // OK for Clang and MSVC
          // GCC error: taking address of temporary array
}

See live code at Compiler Explorer.

My intuition is that *T{} should result in array-to-pointer conversion, and the indirection is well-formed. However, I'm not entirely sure about this.

Is GCC right, or is this a bug? Is it intentional, to prevent developers from making mistakes? After all, you don't usually dereference arrays. Is this documented anywhere?

Disclaimer
CWG Issue 2548 has confirmed that "indirection through an array prvalue is also not valid today". The answer by @StoryTeller is wrong, and misinterprets the meaning of destination type by assuming that this also applies to *T{}, but this expression is not initialization of a pointer.

More discussion at editorial issue EDIT 6555

like image 914
Jan Schultke Avatar asked Aug 11 '26 07:08

Jan Schultke


1 Answers

GCC is right because indirection can only be applied to pointers. [expr.unary.op]/1:

The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result [...]

Note: CWG 1642 and EDIT 3945 makes indirection apply to a prvalue operand.

*arr is OK because arr is an lvalue, and [basic.lval]/6:

Whenever a glvalue appears as an operand of an operator that expects a prvalue for that operand, the lvalue-to-rvalue, array-to-pointer, or function-to-pointer standard conversions are applied to convert the expression to a prvalue.

Array-to-pointer conversion ([conv.array]) is applied toarr.

T{} is already a prvalue (of array type), and there is no wording which necessitates array-to-pointer conversion here, so *T{} is not OK.

like image 146
Language Lawyer Avatar answered Aug 14 '26 06:08

Language Lawyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!