C ++ Articles: Guru of The Week # 1

zhaozj2021-02-08  303

Author: Hub Sutter Translator: plpliuly

/ * This article is the first copy of the GotW (GURU of the Week) series of self-entertainment translation, the original copyright is the author of Hub Sutter (the famous C expert, "Exceptional C " author). The translation of this article did not have the consent of the original author, only for learning discussion. - Translator * /

# 1 The initialization of the variable (proposed on February 21, 97) Difficulties: 4/10 Do you know how many initialization variables? It is necessary to be careful about the initialization of variables, but actually not wrong.

Question: Please see the following statement, is there a difference between them? Sometype T = U; Sometype T (U); Sometype T (); Sometype T;

Workaround: We discussed the above four situations since then: Sometype T; variable T is initialized by the provincial constructor sometype :: SomeType (); this statement has a little "spoof" sex, At first glance, it is a variable declaration. In fact, it is a function declaration. This function does not have a parameter, returns a return value of a SOMETYPE type. Sometype T (U); this is a direct initialization. The variable t is initialized by the constructor Sometype :: Sometype (U). Sometype t = u; this is an initialization, and the variable T is always initialized by the Sometype's copy constructor. (Although there is "=", this is just compatible with C syntax - here is just initialization, and there is no assignment operation, so operators = will not be called.) Semantic: If the variable U is the SomeType type, Then, the above statement is equivalent to the "Sometype T (U)" or calling the SometyPE; if u is other type variables, then the above statement is equal to "SomeType T (Sometype (U))" is equivalent - - That is, U is converted into a temporary Sometype object, and T is constructed in the temporary object copy configuration. Note: For this situation, specific compilers are often allowed (but not required) to optimize performance and save copy construct (that is, direct storage space of the temporary object as a memory space - translator) Note). If this is a compiler, the copy constructor itself must still be accessible.

[Advice]: Try to initialize the variable in the form of "SometyPE T (U)". It is valid for any "Sometype T = U", and has other advantages (for example, it can bring multiple parameters). (End)

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

New Post(0)