C + + Dynamic Memory (Part 2)

Source: Internet
Author: User

Don ' t use the get to initialize or assign another smart pointer.

The code that has the return from get can not delete the pointer

Although the compiler would not complain, it's an error to build another smart pointer to the pointer returned by get

 shared_ptr<int  > P (new  int  (42 )); //  reference count is 1     int  *q = P.get  (); //  OK; but does not delete the its pointer  {shared_ptr  < (q);}  //  block ends. Q is destroyed, and the    Memory to which Q points is freed  int  f = *p; //  undefined. The memory to which P points is freed. 

Using our Own deletion Code

void end_connection (connection *p) {    disconnection (*p);} void F (destination &D) {    = conn (&D);    shared_ptr<connection P (&C, end_connection);     // Use the connection     // When f exists, even if by an exception, the connection resourcewould be properly closed}

For Unique_ptr

Call Release () breaks the connection between a unique_ptr and the object it had been managing. Ofter the pointer returned by release () are used to initialized or assign another pointer

unique_ptr<int> P2 (newint);p 2.release ();     // wrong! P2 the memory, and we have lose the pointerauto P = p2.release ();    // OK, but we must remember to delete p

Backward compatibilities auto_ptr

Although Auto_ptr is still part of the library, programs should use UNIQUE_PTR instead.

C + + Dynamic Memory (Part 2)

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.