Simple implementation of intelligent pointer auto_ptr

Source: Internet
Author: User

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 ;}     
   
  



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.