Real-Life Smart pointer Unique_ptr series in C + +-use std::unique_ptr instead of new operator (Error: ' Unique_ptr ' is not a member of ' STD ')

Source: Internet
Author: User

Wrote a lot about vector blog, in fact, vector is very convenient, but also very simple. But many of the error-prone problems are caused by the smart pointers of the elements in the vector. So decided to start writing a story about smart pointers, especially the unique_ptr pointers.

This is a start, let's use std::unique_ptr instead of new operator!

or using a program to speak:

#include<iostream>int main(){    while (true)        intnewint;}

Look at the memory in Task Manager:

At this point, use the smart pointer unique_ptr:

#include<iostream>#include<memory>int main(){    while (true)        std::unique_ptr<int> x(newint(10));}

Two pictures can clearly see the benefits of smart pointers.

If we release the traditional pointers in time, we can also achieve the effect of smart pointers:

#include <iostream>usingnamespacestd;int main() {    while (true) {        intnewint;        delete x;    }    return0;}

Here's another mistake, the C + + code written on the Mac editor, which uses the smart pointer unique_ptr, when the code is in vs2015, it prompts for an error:
' Unique_ptr ' is not a member of ' STD '

The reason is very simple, is missing unique_ptr header file:

#include<memory>

So you might be wondering when the smart pointer frees up memory?
Unique_ptr objects automatically delete the object they manage (using a deleter) as soon as they themselves is Destro Yed, or as soon as their value changes either by a assignment operation or by a explicit call to Unique_ptr::reset.

The next one will start with the Unique_ptr constructor!!

Real-Life Smart pointer Unique_ptr series in C + +-use std::unique_ptr instead of new operator (Error: ' Unique_ptr ' is not a member of ' STD ')

Related Article

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.