Variable initialization

xiaoxiao2021-03-06  70

There are three ways to initialize variables: mode example ------------------------------------------------------------------------ ------- 1. Call the DEFAULT CTOR T T; 2. Call the CTOR T T (Parameter) of the corresponding parameter type; 3. Call the COPY CTOR T t = u; It is worth noting that at 3, although from the surface Look at there is a = number, but it is not possible to use Assignment Operator, do not be blinded by the surface, which is only used from the C syntax. In addition, when u is a T type object, T T = u; corresponds to T T (u); but if u is other type object, it is equivalent to T T (T (U)), first will Convert into a temporary T object, then call the Copy CTOR constructor. Some compilers will optimize this temporary object, the method is to directly call the type constructor of the U. This optimization process will be conducted by VC7 and BCC32. [Doubt] But Exceptional C said: If this is optimized, the copy constructor is also necessary. But my experiment found: There is no need to have a Copy Ctor, why? Therefore, it is best to use 2 instead of 3, and 2 has a number of parameters when there is an advantage, and 3 can only accept 1 parameters. [experiment] #include usingspace std;

Class T {public: t () {ID_ = count_; cout << "t #" << id_ << "default ctor,"; printcount ();} t (int) {ID_ = count_; cout << "T #" << ID_ << "t (int),"; printcount ();} t (const t & other) {id_ = count_; cout << "t #" << ID_ << " Copy ctor from # "<< isiD_ <<", "; printcount ();} ~ t () {--count_; cout <<" t # "<< id_ <<" destroyed, "; printcount () } T & operator = (const t & rhs) {cout << "t #" << ID_ << "ASSIGNMENT OP FROM #" << rhs.id_ << endl; return * this;}

Private: void printcount () {cound << count_ << "instances exist" << endl;} static int count_; int id_;};

INT t :: count_ = 0;

Int main () {cout << "[1] ---------------------- / n"; T T1; // Call Default CTOR // T red_herring1 (); // function declarationcout << "[2] ---------------------- / n"; t2 (1); / / Call Direct CTOR T T3 (T1); // Call Copy CTOR // T Red_herring2 (T); // Function Declaration

COUT << "[3] ---------------------- / n"; T T4 = 1; // Call Direct CTOR T T5 = T1; // Call Copy CTOR

Cout << "------- Game over! -------- / n";} [OUTPUT] [1] ----------------- ------- T # 1 Default Ctor, 1 Instances EXI [2] ---------------------- T # 2 t (int) , 2 Instances Existt # 3 Copy Ctor from # 1, 3 Instance [3] ---------------------- T # 4 t (int), 4 Instances exist ------- Game over! -------- T # 4 Destroyed, 3 Instances Existt # 3 Destroyed, 2 Instances Existt # 2 Destroyed, 1 Instances Existt # 1 destroyed, 0 instances exist [ Analysis The object T4 is optimized by the compiler, and T :: t (int) is called directly, instead of calling T :: t (int)) to TEMP, then construct [Reference] Exceptional C Item 42 variable initialization- Or is it?

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

New Post(0)