Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

c++ - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...