"C\c++ Learning" 18, c++11 six functions (constructors, moving constructors, moving assignment operators, copy constructors, assignment operators, destructors) __jquery

Source: Internet
Author: User
Tags assert

In C + +, there are three major function copy controls (copy constructors, assignment operators, destructors), while in c++11, move constructors are added to move assignment operators. I would have ventured to name them six functions well.

first, the constructor

C++primer said: A constructor is a special member function that executes a constructor whenever a new object of the class type is created. The job of a constructor is to ensure that the data members of each object have appropriate initial values.

Constructors differ from other functions: constructors and classes have the same name and no return type.

Constructors are the same as other functions: constructors also have physical parameter lists (which can be void) and function bodies. (The constructor for the parameter table is void is the default constructor)

The order in which constructors construct class objects is:1. Memory allocation, constructor invocation when the hermit \ Displays the initialization of each data.

2. Execute the constructor function.

1. Constructor initialization Table

A (): a (0) {}
We initialize the data member using the constructor initialization, but assign a value to the data member in the constructor body without the constructor using the initialization table.

When we write a class, some members must be initialized in the constructor initialization table. (class type member without default constructor, const or reference type member)

When writing code, be aware that you can initialize a const object or a reference type object, but you cannot assign them. That is, we need to complete the initialization before we execute the constructor function body, so the only chance is to initialize the table. From this point you can see that the initialization table is performed before the function body.

In the initialization table, the order in which members are initialized is not in the order in which you write the initialization table, but in the order in which the members are defined.


Initializing a list when initializing a member of a class type, you specify the argument and pass it to a constructor of the member type.

There is an example of a bookstore in C++primer:

Sales-item (): ISBN (9 '), Units_sold (0), Revenue (0.0) {}


When do we have to use the initialization table?

When there is a class member, he is a struct or a class, and there is only one constructor with parameters (no default constructor) at this point we have to initialize the member, we need to invoke the constructor of the member, we need our initialization table, if we do not use initialization table, then memory allocation will be problematic.

Advantages of initializing a list: primarily for custom types, the initialization list is acting on the function body before he invokes the constructor to initialize the object.

However, in the function body, you need to call the constructor first and then assign the value so that the efficiency is not as good as initializing the table.



2, default argument constructor

A (int i = 1): A (i), CA (i), RA (i) {}


3, default constructor

a synthesized default constructor: a function that the compiler automatically generates when a constructor is not defined in a class (note is a constructor).

But we can't rely too much on compilers, and if our classes have compound types or custom type members, we need to define constructors ourselves.

Custom default constructor:

A (): a (0) {}
a (int i = 1): A (i) {}
Perhaps the second constructor is also the default constructor. Yes, because the parameter has a default value.

Let's take a look at a picture, and it will be at a glance:


4. Type conversion

In C++primer, an example of a bookstore problem is passing a string object or a Iostream object into a parameter, an implicit conversion occurs, which can cause problems.

The explicit keyword can suppress implicit conversions.

Explicit Sales_item (const string &book): ISBN (book) {}

If we declare constructors to prevent implicit conversions, you can display other objects to the converted constructor.

String a = "D";
Item.same (Sales_item (a));

second, move the constructor function

The newly added feature in the c++11.

In the last blog I added a diagram, you can see the operation of the mobile constructor principle.


At this point, we stole the memory space of the temporary variable for our own use. Saves time to open up space.

	A (a && h): A (H.A)
	{
		h.a = nullptr;//Remember nullptr.
	}

As you can see, the parameters of this constructor are different, there are two & operators, and the move constructor receives the "right value reference" argument.

And to say, here h.a is empty, and if you don't, h.a executing the destructor at the end of the move constructor will rip away the memory that we stole. The H.A will become a dangling pointer.

When the move constructor is triggered. That is the temporary object (the right value). The move semantics are performed when a temporary object is used.

It should be noted here that the exception occurred, to ensure that the movement of the constructor does not occur exception, you can pass the Noexcept keyword, where you can guarantee that the move constructor thrown out of the exception will directly call the terminate termination program.

Right Value reference:

In the previous blog, we mentioned that the value of the death, he is c++11 new to the right value reference related to the expression.

In C++11, the right value reference is the type that refers to a right value, and the right value usually does not have a name, so we can only find it by reference.

Compare the following two statements:

T &&a = Returna ();
T B = Returnb ();
When a is a right value reference, he is less than B. The process of object destructor and object construction. A directly binds the temporary variable returned by Returna. B is only constructed from the value of the temporary variable.

You should be able to see it clearly. A right value reference is the return of the right value (temporary object) to regain the life cycle. The temporary object is destructor, but the right value reference survives.

Note, however, that the right value reference cannot bind to the left value: int A;   int &&c = A; This is not going to work.


Here's a function that is the move function, which is able to cast the left value to the right value reference.


Move assignment operator

He has the same principle as the mobile constructor, and there is no more to say here.

Give the implementation code:

	A & operator = (a&& h)
	{
		assert (this!= &h);

		A = nullptr;
		A = Move (H.A);
		H.A = nullptr;
		return *this;
	}



Replication control

Iv. Copy Constructors

He is a special constructor with a single formal parameter, which is a reference to the class type. When you define a new object and initialize it with an object of the same type, the copy constructor is used explicitly. The copy constructor is implicitly used when an object of that type is passed to a function or when an object of that type is returned from a function.

You must define a copy constructor:

1. A class has one or more data members that are pointers.

2, a member represents other resources that are allocated in the constructor. Other classes must do some specific work when creating new objects.

The writing of the assignment constructor is given below:

A (const a& h): A (H.A) {}
If you don't want the object to replicate. Then declare the copy constructor as: private;

v. Assignment operators

Like constructors, assignment operators can be overloaded by making different types of right-hand operands.

Assignment and replication are often used together, and this should be noted.

The following gives the assignment operator:

	a& operator = (const a& h)
	{
		assert (this!= &h);

		This->a = H.A;

		return *this;
	}


Vi. destructor Functions

is a complement to a constructor that automatically applies a destructor when an object exceeds the scope or dynamically allocated object is deleted. A destructor can be used to construct or acquire resources during the life of an object when the object is disposed. Regardless of whether the class defines its own destructor, the compiler automatically executes the destructor of a class of non-static data members.

Destructors Run:

Destructors are not executed when an object reference or pointer crosses the bounds, and the destructor is invoked only if the pointer to the dynamically allocated object is deleted or the actual object is out of scope.

To synthesize a destructor :

The compiler always synthesizes a destructor, and the synthetic destructor revokes each non-static member in reverse order when the object is created. Note that the synthesized destructor does not delete the object to which the pointer member is pointing.


The last thing to note is that if a class needs a destructor, he must also copy the constructor and assignment operators.



The end of the blog gives the complete six functions of the code.

#include <iostream> #include <assert.h> using namespace std;
	Class Temp {public:temp (const char* str = nullptr);
	Temp (temp&& t);
	temp& operator = (temp&& t);
	Temp (const temp& t);
	temp& operator = (temp& t);
~temp (void);
Private:char *m_pdata;

};
	Temp::temp (const char* str) {if (!str) {m_pdata = nullptr;
		else {this->m_pdata = new Char[strlen (str) + 1];
	strcpy (This->m_pdata, str);

} temp::temp (temp&& t): M_pdata (Move (T.m_pdata)) {t.m_pdata = nullptr;}

	temp& Temp::operator = (temp&& t) {assert (this!= &t);
	This->m_pdata = nullptr;
	This->m_pdata = Move (T.m_pdata);

	T.m_pdata = nullptr;

return *this;
	} temp::temp (const temp& t) {if (!t.m_pdata) {this->m_pdata = nullptr;
		else {this->m_pdata = new Char[strlen (t.m_pdata) + 1];
	strcpy (This->m_pdata, t.m_pdata); }} temp& Temp::operator = (Temp &t) {if (this!= &t) {delete[] this->m_pdata;
		if (!t.m_pdata) {this->m_pdata = nullptr;
			else {this->m_pdata = new Char[strlen (t.m_pdata) + 1];
		strcpy (This->m_pdata, t.m_pdata);
} return *this;
		} temp::~temp (void) {if (this->m_pdata) {delete[] this->m_pdata;
	This->m_pdata = nullptr; }
}



---2013.12.20

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.