GURU Of THE WEEK Terms 01: Initialization of Variables

zhaozj2021-02-08  516

Gotw # 01 Variable Initialization

Author: Herb Sutter

Translation: Kingofark

[Declaration]: This article takes the Guru of The Week column on www.gotw.ca website, and its copyright belongs to the original person. Translator Kingofark translated this article without the consent of the original person. This translation is only for self-study and reference, please read this article, do not reprint, spread this translation; people download this translation content, please delete its backup immediately after reading. Translator Kingofark is not responsible for people who violate the above two principles. This declaration.

Revision 1.0

GURU Of THE WEEK Terms 01: Initialization of Variables

Difficulty: 4/10

(Think about it, how many ways to initialize variables? Don't pay attention to things that look like "variable initialization".)

[problem]

What is the difference between the following four statements?

Sometype t = u;

Sometype T (U);

Sometype t ();

Sometype T;

[answer]

We examine four statements one by one in the order from the bottom up:

* Sometype t;

The variable T is initialized by the default constructor Sometype :: SomeType ().

* Sometype t ();

This is a scam, because this statement looks like a variable statement, but actually a function declaration; this function T does not have a parameter and return the type of Sometype.

* Sometype T (U);

This is direct initialization. The variable t is initialized by the constructor sometype :: Sometype (U).

* Sometype t = u;

This is the initialization of the copy. The variable T is initialized by the copy constructor of SOMETYPE. (Note, although this statement contains "=", it is still an initialization operation, not an assignment operation, because here, the use of '=' is just in order to follow the syntax of the C language, Operator = is not called of.)

[Semantic Reference]: If u is also the Sometype type, then this statement is equivalent to "Sometype T (U);" is equivalent, and will call the copy constructor of SometyPE. If u is other type other than Sometype, then this statement is equivalent to "Sometype T (Sometype (U))". It can be seen that in the statement "SomeType T (Sometype (U))", U is converted into a temporary Sometype object, but T is constructed thereby constructed.

[Note]: In this case, the compiler can usually (but not necessarily) optimized, appropriate processing copy constructs (generally omitted the copy construction process). If optimized, be sure to ensure the reaches of the copy constructor.

[Learning Guidance]: It is recommended to always use "Sometype T (u)" form, because you can use "Sometype T = U" where it can also be equally, it is because it still has some other advantages. For example, multiple parameters, etc.

转载请注明原文地址:https://www.9cbs.com/read-339.html

New Post(0)