简体   繁体   中英

Address of array prvalue

I don't understand why this doesn't work:

auto a = (int[]){1, 2, 3, 4, 5};

> error: taking address of temporary array

I understand that array lvalues decay to pointers when converted to rvalues but here the array is already an rvalue (actually a prvalue) so no decay should be needed. I would have expected a to be deduced and initialized to int[5] . Why is it trying to take the address of a temporary?

I would have expected a to be deduced and initialized to int[5]

Sadly, this is not how C arrays work. Arrays decays into pointers. You cannot really have an "array value". If you replace auto by the deduced type, it looks like this:

int* a = (int[]){1, 2, 3, 4, 5};

The decay must take the address to make the pointer.

This is easily fixed by using references, since reference to temporaries extends their lifetime:

auto&& a = (int[]){1, 2, 3, 4, 5}; // works!

Here's the example running on compiler explorer .

Of course, with std::array you get a nice syntax and value semantics:

auto a = std::array{1, 2, 3, 4, 5};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM