user1095108
user1095108

Reputation: 14603

returning initializer list mechanism

What mechanism is involved, if when returning types, that are constructible from initializer lists, I don't specify the type I am returning, as in:

std::array<int, 3> make_array()
{
  return { 1, 2, 3 };
}

instead of

std::array<int, 3> make_array()
{
  return std::array<int, 3>{ 1, 2, 3 };
}

Are there any performance penalties involved, if I return the initializer list without specifying a type? Am I actually returning an array, that is converted into a std::array?

Upvotes: 14

Views: 3543

Answers (2)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506985

There are no performance penalties involved. The return value is constructed equivalent to

std::array<int, 3> x = { 1, 2, 3 };

There is not even a single copy or move of an std::array instance involved.

Upvotes: 18

Bartosz Marcinkowski
Bartosz Marcinkowski

Reputation: 6861

The mechanism is just a constructor:

struct X {};

struct Y {
    Y(X);
};

Y f() {
    X x;
    return x;
}

Upvotes: 2

Related Questions