Deep Exploration C ++ object model note (3) constructor, copy constructor, and initialization list

Source: Internet
Author: User

After reading this chapter, I found that the most difficult thing to understand was the copy constructor.
2.1 default constructor.

C ++ standards: For Class X, if there is no user-decleared-constructor, a default constructor will be declared in the dark (implicitly .... A declared default constructor will be a trival (useless) constructor.

If the member attribute of Class X has a constructor, a default constructor needs to be merged in any case. The merged default constructor is used to meet the needs of the compiler, rather than the program.

The following code demonstrates the expansion of the constructor by the compiler:

Class dopey {public: dopey ();} class Sneezy {public: Sneezy (INT); Sneezy ();} class bashful {public: bashful ();} // and a class snow_white {public: dopey; Sneezy; bashful; private: int mumble;}/* If snow_white has such a constructor: // programmer's default constructorsnow_white: snow_white (): Sneezy (1024) {mumble = 2048;} // then the compiler will expand to the following code: C ++ pseudo-code snow_white:: snow_white () Sneezy (1024) {// insert a member Class Object and call its constructor dopey. dopey: dopey (); Sneezy. sneezy: Sneezy (1024); bashful. bashful: bashful (); // The following is the user's code mumble = 2048 ;}

Conclusion: There are four situations that will lead to the synthesis of a default constructor "class with no life constructor. In other cases, the default constructor will not be merged.

1. Class containing "attributes with default constructor.

2. The base class has the default constructor class.

3. classes with virtual functions (because the virtual function table pointer (vptr) should be constructed here)

4. class with a "virtual base class"

C ++ beginners generally have two misunderstandings.: 1) If no default constructor is defined for any class, it will be merged. 2) The default constructor synthesized by the compiler will explicitly set the default value of each data member in the class.

2.2 create copy constructor

If the class does not explicitly declare copy constructor, the class will be completed using default memberwise initialization. If the attributes in the class are also objects, implement memberwise initialization recursively.

Like the default constructor, copy constructor is synthesized by the compiler only when necessary. If Class X has an Attribute Class Object A that has an explicit copy constructor, Class X must synthesize a copy constructor and then call copy constructor of Class.

Do not use bitwise copy semantics (bit-by-bit copy), which is exactly the same as that of default constructor. Therefore, copy constructor must be merged in four cases.

1. Class containing "attributes with copy constructor.

2. The base class has the default constructor class.

3. Class with virtual function (the pointer of vptr needs to be adjusted)

4. class with a "virtual base class"

Let's look at the two classes of the inheritance relationship below.

    class ZooAnimal{                                class Bear:public ZooAnimal{    public:                                         public:        ZooAnimal();                                    Bear();        virutal ~ZooAnimal();                           void animate();        virtual void animate();                         void draw()        virtual void draw();                            virtual void dance();    }                                               }

The second line of the following code is safe, because their vptr originally points to the same virtual function table. For example

Bear Yogi;

Bear Winnie = Yogi;

Zooanimal Franny = Yogi; // This is not safe and sliced occurs. As shown in: the compiler needs to adjust the vptr:

If there is a virtual base class or multiple inheritance, it will be more troublesome. If the programmer does not define a clear copy constructor, the compiler will work well. The following describes how the compiler works:

2.3 Procedural Semantics

The principle of nrv (named return value) is as follows:

X Bar () {x xx; // process x return X ;}

After nrv optimization:

Void bar (X & __result) {// _ result.. X: X (); // directly process _ result instead of X return ;}

Note: To enable nrv optimization, you must manually write a copy constructor.

MemcpyAndMemsetIt is only effective when "class does not include any internal members generated by the compiler (mainly worthy of vptr. If the class declares virtual functions or contains a virtual base class, using the above function will change the initial values of the "internal members generated by the compiler.

class Shape{    public:        Shape() { memset ( this , 0 , sizeof ( Shape ) ) ; }        virtual ~Shape();}

The compiler will expand this constructor into the following

Shape: shape () // constructor C ++ pseudocode {_ vptr _ shape = _ vptl _ shape after expansion ;//Something went wrong: Even if the compiler has just set the value of _ vptr _ shape, it is 0 after memset. Memset (this, 0, sizeof (SHAPE ));};

Copy constructor?

The copy constructor application forces the compiler to partially convert your program. Especially when a function transmits a class object as a value, the class has a copy constructor (whether it is written by you or created by the compiler by default ), this will lead to profound program conversion.

2.4 initialize team members

In the following cases, you must use Member initialization list to enable normal compilation of your program:

1. When initializing a reference member;

2. When initializing a const member;

3. When a constructor of the base class is called and it has a set of parameters.

4. When calling a constructor of a member class, it has a set of parameters.

Note the following:

1: The real sequence of the initialization list is the definition of the Declaration in the header file (by the way, the order in the memory may not be the actual declared order ). Otherwise, some initialization sequence problems may occur.

2: only when class objects exist in the class, such:

class Word{    String _name;    int _cnt;public:    Word(){        _name = 0;        _cnt = 0;        }}

C ++ expands constructor as follows:

// C ++ pseudocode

Word: Word () {// call default constructor _ name. string: string (); // generate temporary object temp string * temp = string (0); // copy _ name; _ name in memberwise. string: Operator = (temp); // destroy the temporary object temp. string ::~ String (); _ CNT = 0 ;}

So what is the result of using the initialization list? C ++ pseudocode:

Word: word: _ name (0) {_ CNT = 0;} word: Word (/* This pointer goes here */) // C ++ pseudocode {// call String (INT) constructor _ name. string: string (0); _ CNT = 0 ;}

Therefore, if it is a basic data type, you do not have to initialize the list. This problem causes some active programmers to put all members in the initialization list for implementation. In this way, C ++ beginners are confused, so that they do not understand the true meaning of the initialization list.

If the above situation appears in the template, it may not be guaranteed!

3. It is best not to use function return values in the initialization list.

Please read in detail,

Ah! Constructor, copy constructor, and destructor are really failures of C ++. Objective-C does not have the objects on the stack, and there are no temporary objects, so there is no burden on the compiler.

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.