[英]Initializer with c++14
Which is the better way to initialize a type in c++14: 这是在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 = . 当我使用{}时 ,它将调用std :: initializer_list的构造函数 ,但结果与=相同。 Have some performance case here?
这里有一些性能案例吗?
int i = 0;
int _initializer_list_i {0};
And here's another case using std::vector<T> : 这是使用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?
一些性能案例?
There will be no performance penalty between operator= and {} init, since, most probably, it will be compiled to same code for int. 在operator =和{} init之间不会有性能损失,因为很可能会将其编译为int的相同代码。
Regarding vector - constructor (a,b) is different from initializer list. 关于向量-构造函数(a,b)与初始化列表不同。
Overall, I would recommend you to read this . 总体来说,我建议你阅读此 。
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. 我个人更喜欢将花括号{}仅用于类似数组的初始化,并且对于构造函数调用使用圆括号(),但它取决于特定的用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.