Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The assignment operator and initialization

I'm studying the C++ programming language and I'm reading the chapter about assignment operator ( = ). In C++ initalization and assignment are operation so similar that we can use the same notation.

But my question is : when i initialize a variable am I doing it with the assignment operator ? When i assign to a variable, am I doing it with the assignment operator ? I think that the only difference is between initialization and assignment because when we initalize a variable we are giving it a new value with the assignmnet operator, when we assign to a variable we are replacing the old value of that variable with a new value using the assignment operator. Is it right ?

like image 865
Piero Borrelli Avatar asked Sep 25 '14 17:09

Piero Borrelli


1 Answers

You asked

when i initialize a variable am I doing it with the assignment operator ?

and said

when we initialize a variable we are giving it a new value with the assignment operator

But, no, you are not. The symbol = is used for both copy-initialization and assignment, but initialization does NOT use the assignment operator. Initialization of a variable actually uses a constructor.

In copy-initialization, it uses a copy constructor.

type x = e; // NOT an assignment operator

First e is converted to type, creating a temporary variable, and then type::type(const type&) initializes x by copying that temporary. type::operator=(const type&) is not called at all.

There is also direct initialization, which does not use the = symbol:

type x(e);
type x{e}; // since C++11
otherclass::otherclass() : x(e) {} // initialization of member variable

While both initialization and assignment give a variable a value, the two do not use the same code to do it.


Further details: With C++11 and later, if there is a move constructor, copy initialization will use it instead, because the result of the conversion is a temporary. Also, in copy-initialization, the compiler is permitted to skip actually calling the copy or move constructor, it can convert the initializer directly into the variable. But it still must check that the copy or move constructor exists and is accessible. And copy constructors can also take a non-const reference. So it might be type::type(type&&) that is used, or type::type(const type&&) (very uncommon), or type::type(type&) that is used, instead of type::type(const type&). What I described above is the most common case.

like image 185
Ben Voigt Avatar answered Nov 14 '22 21:11

Ben Voigt