C ++ Primer Note 9 _ constructor _ copy constructor (deep copy and shortest copy)

Source: Internet
Author: User

1. constructor:


> Constructor is a special member function with the same name as the class. It is used to set an appropriate initial value for each member.

  1. > The constructor cannot return values. The function name is the same as the class name.

  2. > When the default constructor is used, the system automatically calls the default constructor to initialize the object. The default constructor initializes all data members to zero or null. The default constructor is a constructor without parameters.

  3. > When an object is created, the system automatically calls the constructor.


    Features of constructor:

    1.The constructor can be overloaded. The input parameters determine whether to call constructors of different versions.

    2. const cannot be declared as const or virtual. (The Destructor can)

    3. If a class customizes a constructor, the compiler will not generate a default constructor.

    4. Only constructors can initialize member variables in the form similar to the initialization list (especially the const member variables can only be initialized in the initialization list)


    Example:

    # Include
       
        
    # Include
        
         
    Class Person {public: Person (); // default constructor Person (int n, const string & str); // overload of the constructor private: int age; string * name ;};
        
       


    2. Copy Structure


    First introduceDeep copyAndShortest copy:

    > Shallow copy: When copying an object, only simple values are assigned to the data members of the object. By default, the copy constructor executes the shortest copy function. In most cases, "Shallow copy" can work well, but once the object has dynamic members, there will be problems with the shallow copy.

    > Deep copy: when the class member variables have pointer types, we should re-allocate space for the pointer variables when copying objects to avoid copying only pointer values in the shortest copy, so that the two pointers point to the same memory space.


    Example of a copy defect:

    # Include
       
        
    # Include
        
         
    Using namespace std; class Person {public: Person (); Person (int n, const string & str); // overload the constructor ~ Person (); private: int age; string * name;}; Person: Person (): age (0), name (NULL) // list of constructor initialization, you do not need to write the definition! {Cout <"Default Person" <endl;} Person: Person (int n, const string & str): age (n), name (new string (str )) {cout <"Init Person" <endl;} Person ::~ Person () {if (name) {cout <"~ Person "<" name: "<* name <" age: "<age <endl;} delete name;} int main () {Person p1 (10, string ("SCOTT"); Person p2 = p1; return 0 ;}
        
       

    Running result:

    Init Person
    ~ Person name: SCOTT age: 10
    Segmentation fault (core dumped)

    Cause of program crash:

    P2 is obtained by p1 initialization. Since we do not have a custom copy constructor, we call the default copy constructor, which is a shortest copy and only copies the value of name; the name pointer in p1 and p2 points to the same new space. When the Destructor is called, two delete operations may occur and a segment error may occur.

    As shown in:




    Solution:Custom copy constructor! Achieve the effect of deep copy

    Deep copy example: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PC9wPgo8cHJlIGNsYXNzPQ = "brush: java;"> # include # Include Using namespace std; class Person {public: Person (); Person (int n, const string & str); Person (const Person & n );~ Person (); private: int age; string * name;}; Person: Person (): age (0), name (NULL) {cout <"Default Person" <endl;} Person: Person (int n, const string & str): age (n), name (new string (str )) {cout <"Init Person" <endl;} // custom copy constructor Person: Person (const Person & n) {if (n. name) {name = new string (* n. name); age = n. age ;}} Person ::~ Person () {if (name) {cout <"~ Person "<" name: "<* name <" age: "<age <endl;} delete name;} int main () {Person p1 (10, string ("SCOTT"); Person p2 = p1; return 0 ;}

    Running result:

    Init Person

    ~ Person name: SCOTT age: 10

    ~ Person name: SCOTT age: 10
    The preceding solution is feasible because no segment error occurs.





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.