There are many implementation methods for smart pointers. auto_ptr is a relatively poor implementation and does not use reference counting.
Therefore, there are many problems.
In general, the reference counting smart pointer copies the member counting variable and adds a 1. Then, when the count turns to 0, the memory actually points to can be deleted. In this way, the auto_ptr is parsed twice.
The following code is the implementation of auto_ptr. There is no problem in compiling and running vc2005, but there is a problem with VC6. VC6 has poor support for templates.
If the code in VC6 does not call its copy structure.
One problem is that more than tive C ++ 293rd-294 has an implementation of auto_ptr, but I don't know whether it is a compiler problem or the author intentionally mistaken that the Code is not compiled.
The main part is to declare the membership class.
Template Friend class auto_ptr ;
This code can be commented out. You are welcome to discuss this reason. The auto_ptr I implemented under vs2005 is given below.
Hope that the bricks can be thrown and the Jade will come.
Template
Class auto_ptr {public: explicit auto_ptr (T * t = 0): ptr (t) {} template
Auto_ptr (auto_ptr
& Src_ptr): ptr (src_ptr.realse () {printf ("Copy structure! \ N ");}~ Auto_ptr () {delete ptr;} template Auto_ptr & Operator = (auto_ptr & Ptr) {if (this! = & Ptr) {printf ("value assignment structure! \ N "); reset (ptr. realse ();} return * this;} T * operator-> () {return ptr;} T & operator * () {return * ptr;} T * realse () {T * old = this-> ptr; this-> ptr = 0; return old;} void reset (T * src = 0) {if (src! = Ptr) {delete this-> ptr; this-> ptr = src;} private: T * ptr; // template Friend class auto_ptr ;}; Void test () {auto_ptr Test (new int); * test = 100; printf ("% d \ n", * test); auto_ptr Test1 (test); printf ("% d \ n", * test1);} int main (int argc, char * argv []) {test (); system ("pause"); return 0 ;}