C ++ 11 and pointer member copy constructor (and shallow copy deep copy)

[1] shallow copy

All along, the design of a class, personally think that best embodies the local level are: class contains a pointer member variables.

A typical shallow copy following example:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class HasPtrMem
 5 { 
 6 public:
 7     HasPtrMem() : d(new int(0))
 8     {} 
 9     ~HasPtrMem() 
10     { 
11         delete d;
12         d = nullptr;
13     }
14     
15     int* d;
16 }; 
17 
18 int main()
19 { 
20     HasPtrMem a; 
21     HasPtrMem b(a); 
22     
23     cout << *a.d << endl; // 0
24     cout << *b.d << endl; // 0
25 } // 异常析构

It defines the type comprising a pointer member HasPtrMem variable d.

When constructing the member d will accept a new operation of memory allocated heap pointer is returned, and when the destructor will be delete operation for releasing the allocated heap memory.

In the main function, the declared type HasPtrMem a subject, and used to initialize the object is a b. According to the syntax of C ++, which invokes HasPtrMem copy constructor.

The copy constructor and here implicitly generated by the compiler which functions like memcpy performed bitwise copy.

Such a configuration mode has a problem that ad and bd point to the same piece of heap memory.

Thus, when the main end of the scope, and the object a, object b destructor are invoked sequentially.

Wherein when, after completion of one destructor (such as object b to destruction, bd is first delete), ad then it becomes a "dangling" (dangling pointer), because it is no longer effective at the memory.

Then free up memory on the dangling pointer can cause serious errors.

[2] deep copy

Typically, in the case of not declared class constructor, C ++ class will generate a "shallow copy" (shollow copy) constructor.

And the best solution is to a user-defined copy constructor to achieve a "deep copy" (deep copy), correction in cases of deep copy of the results:

. 1 #include <the iostream>
 2  the using  namespace STD;
 . 3  
. 4  class HasPtrMem
 . 5  { 
 . 6  public :
 . 7      HasPtrMem (): D ( new new  int ( 0 ))
 . 8      {}
 . 9      HasPtrMem ( const HasPtrMem & H): D ( new new  int (* HD)) {} // copy constructor, allocate memory from the heap, and with initialization * hd 
10      ~ HasPtrMem () 
 . 11      { 
 12 is          Delete D;
 13 is          D = nullptr a;
14     }
15     
16     int* d;
17 }; 
18 
19 int main()
20 { 
21     HasPtrMem a; 
22     HasPtrMem b(a); 
23     
24     cout << *a.d << endl; // 0
25     cout << *b.d << endl; // 0
26 } // 正常析构

HasPtrMem class adds a copy constructor.

The copy constructor new memory allocated from the heap, the memory allocation pointer back to d, and the use of * (hd) of the initialized * d.

By such a method, avoiding the problems of dangling.

 

good good study, day day up.

Select the cycle order summary

Guess you like

Origin www.cnblogs.com/Braveliu/p/12233571.html