C ++ you may not know

Source: Internet
Author: User
In C ++, the compiler has done many things for us, which we may not know, but may also be used. The following details   I. Initialization and initial assignment First, let's talk about the difference between class initialization and initial assignment. This may be something we don't know. In fact, class initialization is different from initial assignment.

 1           Class  People {  2           Public  :  3 People (STD ::String Name, Int Age, Int  Height );  4           Private  :  5 STD :: String  M_sname;  6                   Int  M_iage;  7                   Int  M_iheight; 8   }  9           //  Assignment  10 People: People (STD :: String Name, Int Age, Int  Height)  11   {  12 M_sname = Name;  13 M_iage =Age;  14 M_iheight = Height;  15   }  16           //  Initialization list  17 People: People (STD :: String Name, Int Age, Int  Height)  18  : M_sname (name), m_iage (AGE), m_iheight (height)  19 {}
C ++ requires that the initialization of the object's member variables takes place before the constructor body. The value assignment of member variables in the constructor is not initialization, but a value assignment. Call the default constructor m_sname, m_iage, and m_iheight to assign an initial value when assigning values, and then call the value assignment operator immediately to assign new values. The initial member list uses the real parameters of each member variable as the real parameters of the replication constructor. So we can see that the assignment is more than initialization, that is, using the assignment operator to assign values. Therefore, Initialization is much more efficient than assignment. However, they are equally efficient for built-in types.   Ii. Empty category Think about what the C ++ compiler will do if you declare an empty class? The compiler will declare a copy constructor, a value assignment operator, a destructor, and a default constructor for it. All these functions are public and inline functions. The value assignment constructor and the value assignment operator written by the compiler simply copies each non-static variable of the source object to the target object, specifically for bit copying. If a constructor is declared, the compiler does not create a default constructor. What if I do not want the class to support the copy constructor and the value assignment operator? Do not declare? According to the above instructions, the compiler will automatically generate for you. You can declare them as private to prevent the compiler from automatically generating the copy constructor (public ). Private successfully blocks others' use, but this is not safe. Because the class member functions and user functions can still call the private copy constructor and the value assignment operator. If you only declare the copy function and the value assignment operator in private, a connection error will be returned when someone calls it through the class member function and the member function. Can errors be reflected during compilation? Here, we only need to declare the copy function as private, and we can do it without ourselves. It is obvious that a base class that inherits a copy function and the value assignment operator is private. The base class is as follows:

 1           Class Noncopyable {  2           Protected  :  3   Noncopyable (){}  4 ~ Noncopyable (){}  5           Private  :  6 Noncopyable ( Const Noncopyable & );  7 Noncopyable & operater = ( Const Noncopyable & );  8 };

The reason is that when a class member function or a friend function tries to copy an object, the compiler will try to generate a copy constructor and a value assignment operator, and call the corresponding function of the base class, but it will be rejected, because the base class functions are private. 3. ++ FunctionsLet's talk about what you don't know in "* ++" and "++ *". c ++ specifies that the auto-increment function with a suffix has an int type parameter, when a function is called, 0 is passed as the value of the int parameter to the function, and the prefix is used as the function. The type parameter is not required, in this way, you can differentiate a ++ function as a prefix and a suffix.CodeAs follows:

 1   Class Upint {  2   Public  3 Upint & Operator ++ (); //  ++ Prefix  4       Const Upint Operator ++ ( Int ); //  ++ Suffix  5 Upint &Operator --(); //  -- Prefix  6       Const Upint Operator --( Int ) //  -- Suffix  7 Upint & Operator + = ( Int ); //  8  ...  9   };  10   11 Upint & upint :: Operator ++ ()  12   {  13 * This + = 1  ;  14       Return * This ;  15   }  16   17   Const Upint :: Operator ++ ( Int  )  18   {  19 Upint oldvalue = * This  ;  20 ++ (* This );  21       Return  Oldvalue;  22 }

The suffix function uses the return parameter type const to prevent the following code from taking effect.

 
1 Upint I;2I ++;

at this time, the cosnt object is returned when ++ is called for the first time, and then call this function again as a non-const member function. Therefore, the const object cannot call this function, so I ++ cannot take effect. here we talk about efficiency, we can see that the suffix ++ function creates a temporary object as its return value. This temporary object is constructed and finally parsed. The prefix ++ function does not have such temporary variables and does not have such operations. Therefore, if we use prefix ++ in the Program , the efficiency will be higher, without the Construction and Analysis of temporary variables. 4. virtual destructor A base class with polymorphism should declare a virtual destructor. Why? See the following example

Class Base{...}ClassDerived:Public Base{...}Base* P =NewDerived;
Assume that the destructor of the base class is not virtual. When the P pointer is used, let's delete it and think about what will happen, because the destructor of the base class is non-virtual, the base class destructor will not be called directly due to polymorphism, and only the contents of the base class in the inheritance class will be deleted, the other memory of the inherited class object is not destroyed, causing resource leakage. If it is declared as virtual, polymorphism will occur. If a pointer is called to the inherited class, the entire inherited class image will be destroyed.   5. reference the transfer method By default, C ++ transfers an object to a function by passing values. Function parameters are based on the actual response of the real parameter, and the call end obtains an attachment of the function return value. These duplicates are produced by the copy constructor. See the following example.

 1           Class  Person {  2           Public  :  3   Person ();  4               Virtual ~ Person ();  5   ... 6           Private  :  7 STD :: String  Name;  8 STD :: String  Address;  9   }  10           11           Class Student: Public  Person { 12           Public  :  13   Student ();  14 ~ Student ();  15   ...  16           Private  :  17 STD :: String  Schoolname;  18 STD :: String  Schooladdress;  19 };

If there is a function to verify whether it is a student

 
1BoolValidatestudent (student s );2 Student Plato;3BoolPlatoisok = validatestudent (Plato );
After analyzing the three lines of code, what does the compiler do? First, call the copy constructor of student and initialize s based on Plato. When validatestudent returns destroyed, the cost is "one-time student copy constructor call, add a student destructor call ". The student object contains two string objects. Therefore, two string objects are constructed. Student inherits from the person object, which contains two strings. Therefore, the total cost of passing a student object by value is "Six constructor and six constructor "!
Passing parameters in the by reference method can also avoid the problem of object cutting. When a derived class object is passed by value and considered as a base class object, the copy constructor of the base class will be called, causing all objects like the derived class to be cut out, only the base class object is left. See the following code to complete polymorphism by passing reference parameters

         Class  Window {  Public  :... STD ::  String Name () Const ;  Virtual   Void Display () Const  ;};  Class Required wwithscrollbars: Public  Window {  Public  :...  Virtual   Void Display () Const  ;}; //  Input the S type and call its display function  //  Input the required wwithscrollbars type and call its display function.  //  Polymorphism          Void Printnameanddispaly ( Const Window & W) {STD: cout < W. Name (); W. Display ();} 

Peat the bottom layer of the C ++ compiler. The reference is often implemented by pointers. Therefore, the pass by reference actually transfers pointers. If the object is in the internal type, the pass by value is more efficient than the pass by reference.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.