C + + Advanced topics replication constructors

Source: Internet
Author: User

Copy Constructors

Consider the definition of the following department type variables:

Department DEPT=QC;

Although this definition looks like an assignment, the operator= function does not work. The purpose of the Operator= function is to assign an existing object to another object. However, the object dept is still not constructed, that is, the pointer dept.address only holds a random value. If you review the implementation code for the Operator= function, you will notice that the first part of the code deletes the original object that the address pointer points to. If you execute the operator= function with an uninitialized object, a fatal error is raised because it attempts to delete a pointer that is not initialized, which results in a program crash or a dynamic memory conflict.

In fact, the compiler will invoke another memory management function---the copy constructor. It defines how one object of a class is constructed as a vice of another object.

If the user does not define a copy constructor, the compiler provides a default copy constructor that simply copies the data members of an existing object to the corresponding data member of the newly created object. For class department, the default copy constructor should include the following actions:

Dept.name=qc.name;

strcpy (dept.address,qc.address);

However, there is a problem with the copy constructor, which will cause the same error as the default assignment operator function. Therefore, you must define a copy constructor to create a copy of the address.

The following is a copy constructor for the Department class:

Department::D epartment (const department& B)
{
cout<< "copy constructor:";
B.print ();
Name=b.name;
if (b.address==null)
Address=null;
Else
{
Address=new Char[strlen (b.address) +1];
Name=b.name;
strcpy (address,b.address);
}
}
assignment operator functions, copy constructors, and destructors are important three parts. They must be implemented in any class that involves dynamic memory management.

As Marshall Cline said: "It's not just a good idea, it's the law." It is not difficult to comply when the law becomes as tax and accepted. The following logical steps should be used when defining these three functions:

destructor (destructor)

Frees all dynamic memory managed by the object.

copy Constructor (copy constructor)

Initializes the object with the secondary of the display parameter object.

Assignment operator function (Assignment Operator)

Test whether the this==&b is true. If it is true, then do nothing.

Frees the dynamic memory of objects that are no longer needed.

Sets the object to display a copy of the Parameter object.

Return to *this.

Note: If you are managing dynamic memory in a user-defined class, you need to consider these three functions. If you use a class library such as a vector or a list, you don't have to consider these.

because these classes have implemented these three corresponding functions.

The following is a test program for the memory management program for these three functions in class department. For testing purposes, the Memory Manager displays trace information.

#include <string> #include <iostream> using namespace std;
	Class Department {public:department (string _name);
	Department (string _name,char* _address);
	~department ();
	department& operator= (const department& b);
Department (const Department &AMP;B);//copy constructor void print () const;
	Private:string name;
char* address;
};
	Department::D epartment (string _name) {name=_name;
	Address=null;
	cout<< "constructor:";
Print ();
	} Department::D epartment (String _name,char* _address) {name=_name;
	Address=new Char[strlen (_address) +1];
	strcpy (address,_address);
	cout<< "constructor:";
Print ();
	} department::~department () {cout<< "destructor:";
	Print ();
delete []address;
	} Department::D epartment (const department& b) {cout<< "copy constructor:";
	B.print ();
	Name=b.name;
	if (b.address==null) address=null;
		else {address=new Char[strlen (b.address) +1];
		Name=b.name;
	strcpy (address,b.address); }} department& department::operator= (const department& b) {cout<< "assignment:";
	Print ();
	cout<< "=";
	B.print ();
		if (this!= &b) {name=b.name;
		Delete[] address;
	    if (b.address==null) address=null;
		    else {address=new Char[strlen (b.address) +1];
		    Name=b.name;
		strcpy (address,b.address);
} return *this;
	} void Department::p rint () const {cout<< "name=" <<name<< ", address=";
	if (address==null) cout<< "NULL";
	else cout<<address;
cout<< "\ n"; }/* void Fun (Department x) {string p=x.name;//error cannot access private variable}*/void Main () {Department ship
	Ping ("Shipping");
	Department QC ("Quality control", "a");
	Department Dept (QC);
dept=shipping; }

program Run Result:

The program has three constructor calls and three matching destructor calls.

Excerpt from: C + + core ideas C + + advanced Topics

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.