Search code examples
c++initializationrvalue-referencestdarray

Can const std::array member reference be initialized with an rvalue?


I was trying to initialize a class member const std::array reference with an initializer list:

class Foo {
    const std::array<const int&, 3> &bar;
    Foo() : bar({ 1, 2, 3 }) {}
}

But apparantly

cannot initialize reference type 'const std::array &' with a parenthesized initializer list

Q: Is there a way to initialize a const std::array reference member with an rvalue?


Solution

  • From the comments on the question I can conclude I didn't realize two things:

    • const reference members aren't the same as const reference non-members, in that they don't extend the lifespan of temporary values.
    • Class members can be initialized in the constructor with curly braces (where applicable, e.g. arrays).

    As an additional note, a member std::array containing T& can cause the following:

    • warning: 'Foo' has virtual functions but non-virtual destructor

    • error: forming pointer to reference type 'std::array::value_type {aka const int&}'

    In both cases, I'm not entirely sure what's going on, but those would be separate questions.