Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning initializer list mechanism

Tags:

c++

c++11

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?

like image 393
user1095108 Avatar asked Jun 21 '13 16:06

user1095108


People also ask

What is the Order of execution of an initializer list?

Generally, the order of execution is from top to bottom and left to right. But a rare condition arises where this rule fails is when the initializer list is used in class. In the initializer list, the order of execution takes place according to the order of declaration of member variables.

When initializer list is used in class in C++?

But a rare condition arises where this rule fails is when the initializer list is used in class. In the initializer list, the order of execution takes place according to the order of declaration of member variables. While using the initializer list for a class in C++, the order of declaration of member variables affects the output of the program.

What is an initializer_list object in Java?

The initializer_list object refers to the elements of this array without containing them: copying an initializer_list object produces another object referring to the same underlying elements, not to new copies of them (reference semantics). The lifetime of this temporary array is the same as the initializer_list object.


2 Answers

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.

like image 144
Johannes Schaub - litb Avatar answered Oct 20 '22 20:10

Johannes Schaub - litb


The mechanism is just a constructor:

struct X {};

struct Y {
    Y(X);
};

Y f() {
    X x;
    return x;
}
like image 45
Bartosz Marcinkowski Avatar answered Oct 20 '22 21:10

Bartosz Marcinkowski