"C + +" smart pointer

Source: Internet
Author: User

VC under the Smart pointer, focusing on ownership of the transfer of # include <iostream>using namespace Std;template<class type>class autoptr{public: autoptr (int *p = null):p TR (P), owns (ptr! = NULL) {}autoptr (const autoptr<type> &t):p tr (t.release ()), owns (T.ow NS) {}autoptr<type>& operator= (const autoptr<type> &t) {if (This! = &t)//Determines whether to assign itself a value of {if (ptr! = T.PTR)//Determine whether to point to the same space {if (owns)//If there is ownership, then free the current space {delete ptr;} Else{owns = t.owns;//Conversely, get ownership}ptr = T.release ();//Let T lose ownership}}return *this;} ~autoptr () {if (owns) delete ptr;} public:type& operator* () Const{return (*get ());} type* operator-> () Const{return get ();} Type* get () Const{return ptr;} type* release () const{((autoptr<type> *const) this)->owns = False;return ptr;} Private:bool owns; Type *ptr;}; int main () {int *p = new int (10); Autoptr<int> PA (p); cout << *pa << Endl; Autoptr<int> PA1 (PA), cout << *pa1 << endl;int *p1 = new int (100); Autoptr<int> PA2 (p1); autoptr<int> pa3;pa3 = Pa2;cout << *pa3 << Endl;return 0;} 




"C + +" smart pointer

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.