C + + Foundation--c++ member functions generated by default

Source: Internet
Author: User
Tags shallow copy

Class Empty

{

Public

Empty (); Default constructor

Empty (const empty&); Copy constructor

~empty (); Destructors

empty& operator= (const empty&); Assignment operators

empty* operator& (); Accessor operator

Const empty* operator& () const; Accessor operator const

};

Default constructor
Destructors
Copy constructor
Assignment operator (operator=)
Accessor operator (operator&) (pair, one non-const, one const)
Of course, all of this can only be produced if needed. For example, if you define a class, but never define an object of that class, or use a function parameter of that type, then there is no basic result. If, for example, you have never had an assignment between objects of that type, then operator= will not be generated.

Class Empty
{
Public
Empty (); Default constructor

Empty (const empty&); Copy constructor

~empty (); Destructors

empty& perator= (const empty&); Assignment operators

empty* operator& (); Value operator
Const empty* operator& () const; Value operator

};


For example, you have the following class:

Class Stringbad
{
Private:
char * STR;
int Len;

Public:
Stringbad (const char * s);
Stringbad ();
~ Stringbad ();

} ;


The definitions of constructors and destructors are defined as follows:

Stringbad::stringbad (const char * s)
{
Len = Std::strlen (s);
str = new Char [len + 1];

}

Stringbad::stringbad ()
{
len = 4;
str = new char [4];

}

Stringbad:: ~ Stringbad ()
{

delete [] str;
}

Then in the program if you have the following code:

Stringbad Sports ("Spinach Leaves Bow1 for bollars");

Stringbad sailor = sports;

What constructors will be called by the second initialization statement above? Remember, this form of initialization is equivalent to the following statement:

Stringbad sailor = Stringbad (sports);

Because the type of sports is Stringbad, the corresponding constructor prototype should be as follows:

Stringbad (const Stringbad &);

When we use an object to initialize another object, the compiler automatically generates the above constructor (called a copy constructor, because it creates a copy of the object).

Now let's see what happens when we call the implicit copy constructor without defining a copy constructor.

As you can see from the code snippet defined by the constructor, when a pointer str is initialized with the new operator, and the implicit copy constructor is copied by value, for the pointer str, the following copy is made:

Sailor.str = Sports.str;

The copy here is not a string, but a pointer to a string! In other words, we will get two pointers to the same string! The resulting problems will be self-evident. When one of the objects calls the destructor, the memory its STR points to will be freed, and if we call another object, what is the address data that Str points to? It is clear that unexpected results will occur.

Therefore, if a class contains pointer members that are initialized with new, you should define a copy constructor to copy the data pointed to, not the pointer, which is called deep copy. Because the default shallow copy (or become a member copy) only shallow assignment pointer information.

Let's look at the following code snippet, and we'll change it a little bit:

Stringbad headline1 ("Celery stalks at midnight");

Stringbad knot;

knot = headline1;

The last line here differs from the above example by assigning an existing object to another existing object, which will take another action, which is to use the overloaded assignment

Operator. (What we need to know is that initialization always invokes the copy constructor, and the assignment operator may be called when using the = operator) because C + + allows objects to be assigned values, which is achieved by automatically overloading the assignment operator for the class. The prototype is as follows:

Class_name & class_name:: operator = (const class_name &);

It accepts and returns a reference to the class object.

As with implicit copy constructors, the implicit object assignment operator also produces the same problem, that is, when you include a pointer member that initializes with new, only shallow copy is used. So we need to use the same workaround, which is to define an overloaded assignment operator for deep replication.

So in summary, if the class contains a pointer member initialized with new, we should explicitly define a copy constructor and an overloaded assignment operator to implement its deep copy to avoid the resulting member replication problem

1. Which of the following functions is a copy constructor, why?

X::X (const x&);

X::x (X);

X::x (x&, int a=1);

X::x (x&, int a=1, b=2);

2. Can there be more than one copy constructor in a class?

3. Write out the output of the following section and explain why? If you can answer the question correctly, you already have a pretty good idea of the copy constructor.

#include <iostream>
#include <string>

struct X {
Template<typename t>
X (t&) {std::cout << "This is ctor." << Std::endl;}

Template<typename t>
x& perator= (t&) {std::cout << "This is ctor." << Std::endl;}
};

void Main () {
X A (5);
X B (10.5);
X C = A;
c = b;
}

The answers are as follows:

1. For a class X, if the first parameter of a constructor is one of the following:

A) x&

b) Const x&

c) Volatile x&

d) Const volatile x&

And no other parameters or other parameters have default values, then this function is a copy constructor.

X::X (const x&);//is a copy constructor

X::x (X&, int=1);//Copy constructor

2. There can be more than one copy constructor in a class.

Class X {
Public
X (const x&);
X (x&); Ok
};

Note that if there is only one copy constructor in a class with a parameter of x&, you cannot use a const x or volatile X object to implement copy initialization.

Class X {
Public
X ();
X (x&);
};

Const X CX;
x x = CX; Error

If a copy constructor is not defined in a class, the compiler automatically produces a default copy constructor.

This default parameter may be x::x (const x&) or x::x (x&), which is chosen by the compiler depending on the context.

The default copy constructor behaves as follows:

The default copy constructor executes the same order as other user-defined constructors, executing the construction of the subclass after the Father class.

The copy constructor performs the action of a member copy (memberwise copy) on each data member in the class.

A) If the data member is an instance of a class, call the copy constructor of this class.

b) If the data member is an array, perform a bitwise copy of each of the pairs.

c) If the data member is a number, such as int,double, then the built-in assignment operator of the system is called to assign the value.

3. Copy constructors cannot be generated by member function templates.

struct X

{
Template<typename t>
X (const t&); Not copy ctor, T can ' t is X

Template<typename t>
perator= (const t&); Not copy the ' t, T can ' t be X
};

The reason is simple, the member function template does not change the language rules, and the language rules say, if the program requires a copy constructor and you do not
have declared it, then the compiler will automatically generate one for you. So the member function template does not prevent the compiler from generating copy constructors, assignment operations
The same rules apply to the overloaded characters. (see effective C + + 3edition, ITEM45)

C + + Foundation--c++ member functions generated by default

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.