C ++ 11:v = {}和v {}之间的差异 [英] C++11: Difference between v = { } and v { }
本文介绍了C ++ 11:v = {}和v {}之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想询问以下两个语句之间是否有任何区别:
I would like to ask if there is any difference between following two statements:
// C++11
std::vector<int> d {1, 2, 3};
std::vector<int> d = {1, 2, 3};
在这两种情况下,都会调用序列构造函数:
In both cases the sequence constructor gets invoked:
class A {
public:
int a;
A() {
cout << "default constructor" << endl;
};
A(const A& other) {
cout << "copy constructor" << endl;
};
A& operator =(const A& other) {
cout << "assignment operator" << endl;
}
A(std::initializer_list<int> e) {
cout << "sequence constructor" << endl;
};
A& operator =(std::initializer_list<int> e) {
cout << "initializer list assignment operator" << endl;
}
};
int main(int argc, char** argv) {
A a {1, 2}; // sequence constructor
A b = {1, 2}; // sequence constructor
b = {1, 2}; // initializer list assignment operator
}
推荐答案
例如
A myA{...};
将始终调用适当的构造函数。
will always invoke the appropriate constructor.
但是
A myA = ...;
将根据作业右侧的表达式执行不同的操作,调用复制构造函数。
will do different things depending on the expression on the right-hand side of the assignment, as it might invoke the copy-constructor instead. Or optimize it out with copy-elision.
此外,如果你有一个数组,你必须使用赋值语法。
Also, if you have an array you have to use the assignment syntax.
这篇关于C ++ 11:v = {}和v {}之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文