#include <array>
int main()
{
struct A
{
unsigned char l;
std::array<char, 12> c;
};
const A a = {1, "t"}; // OK
const A& ar = {1, "t"}; // error: invalid initialization of reference of type 'const main()::A&' from expression of type '<brace-enclosed initializer list>'
}
(gcc 8.2, -std=c++17)
This question talks about a GCC bug, but it's old (7 years ago).
Note that I don't care about lifetime extension, I'm actually passing the temporary directly into a function for use rather than store it but I tried making the example clean.
Edit:
- I cannot make the example smaller. In particular, it has to do with the
array<char>
. - Adding more braces around "t" and still fails.
Something that works is exploding the string literal into characters:
const A& ar = {1, {'a', 'b'}}; // works
const A& art = A{1, "ab"};
This would sort it for what I'm doing – Lowspiritedstd::array<char, 12> c{"hello"};
. Although a raw array member of typeT[N]
is the most likely implementation, the Standard only says that astd::array<T,N>
is an aggregate which can be list-initialized from an initializer list with up toN
elements. So an implementation liketemplate <class T, size_t N> struct array { T __elem; array<T, N-1> __rest; };
would also be compliant. – Ensuredata()
member (unless maybe the implementation knows indexing the elements as array elements will work in practice). But @Tse I don't see any requirement thatstd::array
contains an array element. – Ensure