Objective STL Study Notes for C ++ Item7

Source: Internet
Author: User

Suppose we have the following code:

<Widget*> ( i = ; i < SOME_MAGIC_NUMBER; ++}                

Widgets in the Code are a class. Obviously, this code segment may cause memory leakage. After the function is executed, every vwp element is destroy, but the Widget object we use is not deleted. Oh, no! Memory leakage!

Some people may want to talk about it. This is not simple. I will delete them and it will not be over. Add the following code at the end of the doSomething function:

( vector<Widget*>::iterator i = vwp.begin(); i != vwp.end(); ++*i;

However, is there any more elegant method for this situation? Maybe you can use the function object to accomplish this. It seems like a bit of high-end atmosphere:

 DeleteObject {                            template<typename T>                          ()( T* ptr) <SpecialString*>
 
}

This method looks good, and we have released the pointer elegantly. But is there no better way? The good news always comes late, and the smart pointer comes on stage. In the C ++ 11 standard, the smart pointer is located in the header file of the std namespace <memory>, you need to add related statements when using them (Here we use cmd_ptr ):

#include <memory> std::shared_ptr;

The preceding problem can be solved as follows:

<Widget> SPW;
    vector<SPW> ( i = ; i < SOME_MAGIC_NUMBER; ++ Widget));
    ...
}                                   

Thank you for reading this article. I hope it will help you!

Published by Windows Live Writer.

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.