How Many Ways Are The The INITIALIZE VARIABLES? DON 'THAT TO WATCH OUT for Bugs That Look Like Variable Initialization, But Aren't.
Problem
What is the difference, if any, between the folowing?
Sometype t = u;
Sometype T (U);
Sometype t ();
Sometype T;
Solution
Taking Them in Reverse Order:
Sometype T;
The variable t is initialised using the default ctoro type :: sometype ().
Sometype t ();
.
Sometype T (U);
This Is Direct Initialisation. The Variable T IS INIALISED Using Sometype :: SomeType (U).
Sometype t = u;
This is copy initialisation, and the variable t is always initialised using SomeType's copy ctor. (Even though there's an "=" there, that's just a syntax holdover from C ... this is always initialisation, never assignment, and so operator = is Never Called.) Semantics: IF U Also Has Type Sometype, this is The Same AS "SomeType T (U)" And Just Calls Sometype's Copy Ctor. IF u is of some of the other other type, the this is the same as "SomeType T ( SomeType (u)) "... that is, u is converted to a temporary SomeType object, and t is copy-constructed from that Note:. The compiler is actually allowed (but not required) to optimize away the copy construction in this Kind of Situation. If IT DOES OPTIMIZE IT, The COPY CTOR MUSTSELL BE, The COPY CTOR MUST STILL BE Access. [Guideline] Prefer Using The Form "Sometype T (U)". IT Always Works Wall "Sometype T = U" Works, And Has Other Advantages For instance, it can take multiple parameters. Chinese: How many ways to initialize variables? Be careful to prevent those look like an initialization variable, but actually is not a problem. problem:
Is there any difference between the following code? If it is different, what is the difference between different points? Sometype T = U; SomeType T (); SomeType T (); Sometype T; Answer: OK, I will come from the last one: Sometype T; Variable T uses the default constructor sometype :: sometype () to initialize . Sometype T (); Be careful, don't be up, it looks like a declaration of a variable T, but, in fact, it is a function T () statement. Sometype T (U);