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
}
Doing e.g.
will always invoke the appropriate constructor.
But doing
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.