Declare a copy constructor and a value assignment operator for classes requiring dynamic memory allocation

Source: Internet
Author: User
Let's look at the following class that represents a String object:
// A simple string class

Code

Class   String {
Public :
String ( Const   Char   * Value );
~ String ();
... // No copy constructor and operator =
Private :
Char   * Data;
};
String :: String ( Const   Char   * Value)
{
If (Value ){
Data =   New   Char [Strlen (value) +   1 ];
Strcpy (data, value );
}
Else {
Data =   New   Char [ 1 ];
* Data =   ' \ 0 ' ;
}
}

 

Inline string ::~ String () {Delete [] data ;}
Note that the assignment operator and copy constructor are not declared in this class. This will cause some adverse consequences.
If two objects are defined as follows:
String A ("hello ");
String B ("world ");
The result is as follows:
A: Data --> "Hello \ 0"
B: Data --> "world \ 0"
Object A is a pointer to the memory containing the string "hello", and object B is a pointer to the memory containing the string "world. If
Value assignment below the row:
B =;
Because no custom operator = can be called, C ++ will generate and call a default operator = Operator (see clause 45 ). This default value assignment operator
Assign values to members one by one from members of a to members of B. For pointers (A. Data and B. data), the values are copied one by one. The assignment result is as follows:
A: Data --------> "Hello \ 0"
/
B: Data --/"world \ 0"
In this case, there are at least two problems. First, the memory that B once pointed to will never be deleted, so it will be lost forever. This is a typical example of Memory leakage. The
2. Now the pointers in A and B point to the same string. As long as one of them leaves its living space, The Destructor will delete the other pointer.
Memory. String A ( " Hello " ); // Define and construct
{ // Opening a new living space
String B ( " World " ); // Define and construct B
...
B = A; // Execute operator =,
// Memory loss of B
} // Exit the living space and call
// B's destructor
String C = A; // C. The data value cannot be determined!
// A. Data has been deleted.

In this example, the last statement calls the copy constructor because it is not defined in the class. c ++ generates a copy structure in the same way as the assignment operator.
Create a function and execute the same action: copy the pointer in the object bit by bit. This causes the same problem, but there is no need to worry about memory leakage because
The object cannot point to any memory. For exampleCodeWhen C. Data is initialized with A. data value, there is no memory leakage because C. Data does not point to any
Anywhere. However, if C is initialized by A and C. Data and A. data point to the same place, this place will be deleted twice: once C is destroyed, another time
When a is destroyed.
The copying of constructors is different from the assignment operator. When the value is called, it may cause problems. Of course, as stated in cla22, there are very few
Call the object to pass the value, but let's take a look at the example below:

Void Donothing ( String Localstring ){}
String S =   " The truth is out there " ;
Donothing (s );

 

everything seems normal. However, because the passed localstring is a value, it must be initialized from s through the (default) copy constructor. Therefore, localstring
has a copy of the pointer within one second. When donothing stops running, localstring leaves its living space and calls the destructor. The result will also be: the s package
contains a pointer to the memory that has been deleted by localstring.
by the way, it is unpredictable to use Delete to delete a deleted pointer. So even if s is never used, it may cause problems when it leaves its living space
.
the solution to this type of pointer disorder is to write your own copy constructor and value assignment operator functions as long as there are pointers in the class. In these functions
, you can copy the data structures pointed to so that each object has its own copy; alternatively, you can use a reference counting mechanism (see the terms
m29) to track the number of objects currently pointing to a data structure. The reference counting method is more complex, and it requires more work within the constructor and destructor
, but in some (although not all) Program , it saves a lot of memory and effectively improves the speed.
for some classes, it is very troublesome to implement the copy constructor and value assignment operator, especially when you are sure that the program will not perform the copy and value assignment operations,
implementing them will be a little less than worth the candle. The example that omitted the copy constructor and the value assignment operator mentioned above is, of course, a bad setup
. In reality, it is impractical to implement them, what should I do? Simply put, follow the suggestions in these terms: You can declare these functions (the sound
is a private member) rather than define (implement) them. This prevents someone from calling them and the compiler from generating them.

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.