Lukas Man
Lukas Man

Reputation: 115

Initializer with c++14

Which is the better way to initialize a type in c++14:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    // your code goes here
    int i = 0;
    int _initializer_list_i {0};
    std::cout << "Initialize with = " << std::to_string(i); 
    std::cout << "Initialize with std::initializer_list " << std::to_string(_initializer_list_i);

    std::cout << "\nNormal intialize: \n";
    std::vector<int> v(10, 22);
    for(auto it = v.begin(); it != v.end(); it++)
        std::cout << *it << "\n";


    std::cout << "\n\nUsing intializer_list: \n";    
    std::vector<int> v2{10, 22};
    for(auto it = v2.begin(); it != v2.end(); it++)
        std::cout << *it << "\n";

    return 0;
}

When I use {}, it calls the constructor for std::initializer_list, but the result is the same as with =. Have some performance case here?

int i = 0;
int _initializer_list_i {0};

And here's another case using std::vector<T>:

std::vector<int> v(10, 22);//allocate 10 with value 22
std::vector<int> v2{10, 22}; //Call std::initializer_list with 2 positions{10, 20}

Which is the better way to initialize? Some performance case?

Upvotes: 1

Views: 573

Answers (2)

spraetor
spraetor

Reputation: 451

The difference between () and {} initialization is sometimes a bit irritating - in which cases is there a difference, in which cases is it exactly the same bahavior? That's why there exist a couple of very nice articles about this topic: I want to mention just a few:

I personally prefer to use the curly braces {} for array-like initialization only and for constructor calls the round brackets (), but it depends on the specific use-case.

Upvotes: 0

Starl1ght
Starl1ght

Reputation: 4493

There will be no performance penalty between operator= and {} init, since, most probably, it will be compiled to same code for int.

Regarding vector - constructor (a,b) is different from initializer list.

Overall, I would recommend you to read this.

Upvotes: 1

Related Questions