C + + Smart pointers and their simple implementation

Source: Internet
Author: User

This will mainly introduce smart pointers shared_ptr and unique_ptr, and simply implement a smart pointer based on reference counting.

Since c++11, the C + + standard provides two types of smart pointers:

1. Class shared_ptr implements the concept of shared-ownership (GKFX ownership). Multiple smart pointers can point to the same object, and the object and its related resources are released when the last reference (reference) is destroyed. To perform the above work in a complex structure, the standard library provides auxiliary classes such as weak_ptr, Bad_weak_ptr, and Enable_shared_from_this.

2. Class Unique_ptr implements an exclusive owning (exclusive ownership) or strictly owned (strict ownership) concept, guaranteeing that only one smart pointer can point to the object at the same time. It is particularly useful for avoiding resource leaks (resourece leak)-such as "forgetting to call delete after an exception has been created with new."

Note: Class auto_ptr in c++98 is no longer recommended for use in c++11.

shared_ptr

Unique_ptr

Simple implementation of smart pointers

C + + Smart pointers and their simple implementation

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.