1

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?

4
  • 2
    Those constructors have different effect, how are you going to compare which is better way to initialize? Also, don't try to optimize such things until you definitely know there is a bottleneck there. Commented Nov 13, 2015 at 20:06
  • the result is the same that {operator=}? The code you show never once uses operator= Commented Nov 13, 2015 at 20:13
  • 3
    "Which is better" is vague without criteria. Most of your terminology is off -- for example, there is no operator= use in the above code. int x = 3; does not involve operator=. Please be more specific in what you mean by "better". Commented Nov 13, 2015 at 20:15
  • I was wondering if there is any difference in code quality(design patterns) to initialize with or = std :: initializer_list, or if it's just a matter of preference programmer? it depends of the code?e.g Initialize with {} should be uses in this cases Commented Nov 13, 2015 at 21:29

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.