Summary of C + + constructor functions

Source: Internet
Author: User
Tags bitwise

constructor is a very basic C + + knowledge point, in peacetime programming, I believe we are very familiar with, although the comparative basis, but scrutiny down, or there are a lot of details to pay attention to. This article mainly summarizes the C + + constructor need to pay attention to some details, on the one hand, can help everyone to consolidate this knowledge. At the same time, but also helps oneself better to tidy up prior knowledge.

Let's start with the creation of an object. When an object is created, the compiler calls the constructor of the object, and at this point, there may be questions: I don't specify a constructor for the object, so where does the compiler call constructor come from?

This is a good start, so when we don't specify a constructor, where does the compiler call the constructor? , the answer is that the compiler will produce the required constructors for the object itself.

So now there are two more questions:
>1. Under what conditions will the compiler automatically generate default constructors for us?
>
>2. What does the auto-generated constructor mainly do?

Let's first answer question 1, the answer is:
> When we don't have an object to specify a constructor, the compiler generates a default constructor for us, a copy constructor, and a default destructor.

In this case, we can do this by using a copy to construct an object, whether we use new or not. Here you need to mention the difference between a copy constructor and an assignment constructor, see the following example:

class // declares an object obj //  OBJ B (a); // Call the default copy constructor to construct the object OBJ C = b; // the copy constructor is also called, preferably written as OBJ C (b). 

So, when we don't need a compiler-generated constructor, it should be clear that if you declare your own constructor, copy the constructor, the compiler will not generate these functions for us.
By taking advantage of this we can restrict the generation of objects, for example, by declaring the default constructor, the copy constructor as private, to prevent the outside world from producing this object, which is mainly used in singleton mode.

In the above we understand the conditions in which the compiler automatically generates functions for objects. Let's take a second question.

In this issue, two constructors are included: the default constructor and the copy constructor. Next we will answer this question separately.

1. What do the compiler-generated default constructors do primarily?

The actual representation in this problem is inaccurate because, by standard, the compiler produces a default constructor that conforms to the compiler's requirements only when it is needed, and in other cases does not produce a default constructor because it is not required. So what is the time when it is needed? The answer is:

>1. The internal member variable has a default constructor, and if there are multiple member variables, the default constructor for the member variable is invoked in the order in which the member variable is declared. The

>2. Base class has a default constructor. When you construct a subclass, you need to construct the parent class first. A virtual function is declared in the

>3. class because the compiler needs to specify the correct address for the virtual function table pointer in the class.

>4. With virtual base classes (virtual base class). Because the compiler needs to determine the offset of the virtual base class in the object to make it easier to invoke the data in the virtual base class.

In the above four cases, the compiler will synthesize the default constructor for the object, and in the case above, you can also know what the default constructor of the compiler composition does (this knowledge point is described in detail in the Deep Exploration C + + object model). It is also important to note that the default constructor for the compiler composition does not initialize member variables, and if you want to specify a specific value for the member variable in the construct, you need to refer to the setting in the custom constructor.

The first question can come to an angle, let's see what the default copy constructor does.

Before you answer this question, let's review the invocation time of the copy constructor, and call the copy constructor

>1 of the object in the following three scenarios. The value of one object as the initial of another object. For example:

Class= A; OBJ C (a);

>2. When a parameter is used as a function. For example:

class obj{}; void Foo (obj obj);

>3. When the return value of a function is used. For example:

class obj{};obj foo () {    obj obj;     return obj;//calls the copy constructor. }

By the second case above, * * The use of reference parameters in a function can reduce the construction of the object * *.

To understand the timing of the copy constructor call, let's see what the compiler generated default copy constructors do. The default copy constructor primarily functions as a bitwise copy and, when necessary, inserts some other behavior in addition to a bitwise copy, as detailed in the previous article----[C + + copy constructor summary] (http://www.cnblogs.com /yetuweiba/p/3390853.html). In implementing the copy constructor we need to pay attention to a little bit of deep copy and shallow copy to prevent the copying of incomplete errors.

above is the basic knowledge of the syntax of the constructor, according to the above principle, you can summarize some error-prone areas, see below.

>1. If the object has member variables, you need to set the initial value in the custom constructor and initialize the member variables with the member initialization list whenever possible. At the same time, member variables are constructed in the order in which they are declared, so be aware of dependencies.

Initializes a member variable in the constructor, and in the compiler it actually calls the constructor of the member variable and then calls its assignment function, so using the member initialization list saves efficiency. The construction of

member variables is done in the order in which they are declared, so do not let member variables that are declared earlier rely on member variables that are declared late. Example below

class obj{private:    int  A;     int b; // The following constructor is the wrong OBJ (constint1)    //  error, at which point B is not yet constructed, the value of a is unpredictable.  //  The correct approach is to change the order of declarations of A and B, and also replace the order of A and B in the member's initial session list {}};

>2. It is prudent to call a virtual function in the constructor (it is best not to call the virtual function in the constructor).

Let's first cite an example:

 class   base{Base () {fun ();  // error, when the call is base fun, a call error occurs.   " virtual  void  Fun () = 0   class     Derivate: public   base{derivate () {};  virtual  void   Fun () {std::cout  <<  i am Der    Ivate   << Std::endl; }};D erivate D;  

In the above code, the construction of D will cause an error, because the base class is constructed earlier than the derived class, and when the base class is constructed, it is not dropped into the derived class, that is, only the function of the base class is called, and the fun in base is the virtual function, and an error occurs. Although we can call fun in the Derivate constructor, doing so means there is a problem with the design of the interface. Therefore, it is best not to call virtual functions in constructors.

>3. In a concurrency environment, pay attention to the security of the constructor.

When in a concurrent environment, the original simple things will become complex. We all know that in a concurrent environment, the execution of a thread is chaotic, and we get a pointer to the object, which is pointing to a constructor that performs a generic object, such as:

class  Public observer{    //  error    Foo (Observable * s)    {        s->register (  this)    }}

The above example is unsafe because it is registered in the constructor, and the object may still not be fully constructed. If, Foo is accumulating, then the derived class is not yet constructed, and an error is raised at the time of registration. So, the above example shows that the this pointer (aboutspeaker) is not exposed during object construction. One way to resolve the above error is to "two-segment construction", that is, after the object construction is complete, exposing the this pointer externally.


The above is about C + + in some of the structure of the summary, if there is a wrong place, please give us a lot of advice, thank you. In addition, do not support markdown, some inconvenient.

Summary of constructor functions for C + +

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.