This is a excellent article about destructor, copy constructor and copy assignment operator.Original text is http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three.
Introduction
C ++ treats variables of user-defined typesValue Semantics. This means that objects are implicitly copied in various contexts, and We shoshould understand what "copying an object" actually means.
Let us consider a simple example:
ClassPerson {STD ::StringName;IntAge;Public: Person (ConstSTD ::String& Name,IntAge): Name (name), age (AGE ){}};
Int main ()
{
Person A ("Bjarne stroustrup", 60 );
Person B (a); // What happens here?
B = A; // and here?
}
(If you are puzzled by the name (name), age (AGE) part, this is called a member initializer list .)
Special member functions
What does it mean to copy a person object? The main function shows two distinct copying scenarios. The initialization person B (a); is already med byCopy constructor. Its job is to construct a fresh object based on the state of an existing object. The assignment B = A is already med byCopy assignment operator. Its job is generally a little more complicated, because the target object is already in some valid State that needs to be dealt.
Since we declared neither the copy constructor nor the assignment operator (nor the destructor) ourselves, these are implicitly defined for us. Quote from the standard:
The [...] copy constructor and copy assignment operator, [...] and destructor are special member functions .[Note:The implementation will implicitly declare these member functions for some class types when the program does not explicitly declare them.The implementation will implicitly define them if they are used. [...]End note] [N3126.pdf section 12 § 1]
By default, copying an object means copying its members:
The implicitly-defined copy constructor for a non-union Class X performs a memberwise copy of its subobjects. Limit n3126.pdf section 12.8 § 16]
The implicitly-defined copy assignment operator for a non-union Class X performs memberwise copy assignment of its subobjects. Limit n3126.pdf section 12.8 § 30]
Implicit Definitions
The implicitly-defined special member functions for person look like this:
// 1. copy constructor person ( const person & that): Name (that. name), age (that. age) {} /// 2. copy assignment operator person & operator = ( const person & that) {name = that. name; age = that. age; return * This ;} /// 3. destructor ~ person () {}
Memberwise copying is exactly what we want in this case: name and age are copied, so we get a self-contained, independent person object. the implicitly-defined destructor is always empty. this is also fine in this case since we did not acquire any resources in the constructor. the members 'destructors are implicitly called after the person destructor is finished:
After executing the body of the Destructor and destroying any automatic objects allocated within the body, a destructor for Class X callthe Destructors for X's direct [...] members limit n3126.pdf 12.4 § 6]
Managing Resources
So when shoshould we declare those special member funber explicitly? When our classManages a resource, That is, when an object of the class isResponsibleFor that resource. That usually means the resource isAcquiredIn the constructor (or passed into the constructor) andReleasedIn the destructor.
Let us go back in time to pre-standard C ++. there was no such thing as STD: string, and programmers were in love with pointers. the person class might have looked like this:
Class Person { Char * Name; Int Age; Public : // The constructor acquires a resource: // In this case, dynamic memory obtained via new [] Person ( Const Char * The_name, Int The_age) {name = New Char [Strlen (the_name) + 1 ]; Strcpy (name, the_name); age = The_age ;} // The Destructor must release this resource via Delete [] ~ Person () {Delete [] Name ;}};
Even today, people still write classes in this style and get into trouble :"I pushed a person into a vector and now I get crazy memory errors!"Remember that by default, copying an object means copying its members, but copying the name Member merely copies a pointer,NotThe character array it points! This has several unpleasant effects:
- Changes via a can be observed via B.
- Once B is destroyed, A. Name is a dangling pointer.
- If a is destroyed, deleting the dangling pointer yields undefined behavior.
- Since the assignment does not take into account what name pointed to before the assignment, sooner or later you will get memory leaks all over the place.
Explicit definitions
Since memberwise copying does not have the desired effect, we must define the copy constructor and the copy assignment operator explicitly to make deep copies of the character array:
// 1. copy constructor Person ( Const Person &That) {name = New Char [Strlen (that. Name) + 1 ]; Strcpy (name, that. Name); age = That. Age ;} // 2. Copy assignment operator Person & Operator = ( Const Person & That ){ If ( This ! = & That) {Delete [] Name; // This is a dangerous point in the flow of execution! // We have temporarily invalidated the class invariants, // And the next statement might throw an exception, // Leaving the object in an invalid state :( Name = New Char [Strlen (that. Name) +1 ]; Strcpy (name, that. Name); age = That. Age ;} Return * This ;}
Note the difference between initialization and assignment: we must tear down the old state before assigning to name to prevent memory leaks. also, we have to protect against self-assignment of the form X = x. without that check, delete [] Name wocould Delete the array containingSourceString, because when you write x = x, both this-> name and that. Name contain the same pointer.
Exception safety
Unfortunately, this solution will fail if new char [...] throws an exception due to memory exhaustion. One possible solution is to introduce a local variable and reorder the statements:
// 2. Copy assignment operator Person & Operator = ( Const Person & That ){ Char * Local_name = New Char [Strlen (that. Name) + 1 ]; // If the above statement throws, // The object is still in the same state as before. // None of the following statements will throw an exception :) Strcpy (local_name, that. Name); Delete [] Name; Name = Local_name; age = That. Age; Return * This ;}
This also takes care of Self-assignment without an explicit check. an even more robust solution to this problem is the copy-and-swap idiom, but I will not go into the details of exception safety here. I only mentioned exceptions to make the following point:Writing classes that manage resources is hard.
Noncopyable Resources
Some resources cannot or shocould not be copied, such as file handles or mutexes. In that case, simply declare the copy constructor and copy assignment operator as private without giving a definition:
Private: Person (ConstPerson &That); person&Operator= (ConstPerson & that );
Alternatively, you can inherit from boost: noncopyable or declare them as deleted (C ++ 0x ):
Person (ConstPerson & that) =Delete; person&Operator= (ConstPerson & that) = Delete;
The rule of three
Sometimes you need to implement a class that manages a resource. (never manage multiple resources in a single class, this will only lead to pain.) In that case, rememberRule of three:
If you need to explain icitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explain icitly declare all three of them.
(Unfortunately, this "rule" is not enforced by the C ++ standard or any compiler I am aware .)
Advice
Most of the time, you do not need to manage a resource yourself, because an existing class such asstd: String already does it for you. just compare the simple code using a STD: String member to the convoluted and error-prone alternative using a char * and you should be convinced. as long as you stay away from raw pointer members, the rule of three is unlikely to concern your own code.