Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use C++ Smart pointer shared_ptr

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to use C++ smart pointer shared_ptr". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. What is shared_ptr?

A variety of pointers in clocking 11, including shared_ptr, are template types, meaning that the user can specify the type of action he wants.

You can create a shared_ptr as follows:

What operations are supported by shared_ptrp1; / / p1=NULL2 and shared_ptr?

Create: shared_ptr p = make_shared

Determine whether it is NULL:if (p)

Get the pointing object

Wait

3. How to create an instance of shared_ptr?

Dynamically apply for object memory through the make_shared () function in C++ 's standard library, and return the shared_ptr of this object:

Shared_ptrp1; p1 = make_shared; 4. What is the reference count of shared_ptr? How do I view it?

Because it allows multiple shared_ptr to point to the same object, C++ supports "reference counting", that is, counting how many shared_ptr points to the same object. When the shared_ptr of an object increases, the reference count increases by one; when the shared_ptr of an object decreases, the reference count decreases by one.

The function member of the use_count of the shared_ptr object returns the reference count value:

Shared_ptrp2, p3positionp2 = p1utterp3 = p1scarp / p1nominep2menp3 points to the same object, so the referenced technical value is 3cout.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report