1

Move supports to steal temporary object's internals to avoid copying. Is it possible to create raw array of temporary objects? i.e. vector does not belong to this category.

struct Employee{};

Employee{}; // this creates temporary
Employee [10]; // compiler error, expected identifier before numeric constant
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
Nandha
  • 139
  • 1
  • 5

2 Answers2

1

Yes, there can be materialized array prvalues. You need to use a type alias though, as the type specifier for the case T{} must be a single identifier:

using array_t = Employee[10];
array_t{};

The prvalue can undergo array-to-pointer conversion too, e.g.:

void func(Employee const* ptr);
// ...
func( array_t{} );
M.M
  • 138,810
  • 21
  • 208
  • 365
0

The only good way to prolong the lifetime of the temporary is to get and hold reference to const to it.

Something like this might work

using Ecref = const Employee&;

Ecref a[10] = {Employee("John"), Employee("Mary"), ...};

But, unfortunately, arrays of references (const and non-const as well) are forbidden in C++.

Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64