Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: Difference between v = { } and v { } [duplicate]

Tags:

c++

c++11

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
}
like image 1000
MeJ Avatar asked Mar 16 '14 09:03

MeJ


People also ask

What is the difference between C ++ 98 and C++11?

C++98 defined only one smart pointer class, auto_ptr , which is now deprecated. C++11 includes new smart pointer classes: shared_ptr and the recently-added unique_ptr.

What does auto do in a for loop?

Range-based for loop in C++ Often the auto keyword is used to automatically identify the type of elements in range-expression.

Which of the following is a function added in C++11?

For that C++11 introduces two new special member functions: the move constructor and the move assignment operator.

How do you create a range in CPP?

Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .


1 Answers

Doing e.g.

A myA{...};

will always invoke the appropriate constructor.

But doing

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.

like image 78
Some programmer dude Avatar answered Sep 28 '22 19:09

Some programmer dude