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

The use of C++ Smart pointer weak_ptr

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article introduces the knowledge of "the use of C++ smart pointer weak_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!

Smart pointer weak_ptr uses weak_ptr for: 1, to solve the problem of hanging pointer 2, to solve the problem of circular reference weak_ptr features: there is no * operation and-> operation weak_ptr is a smart pointer that does not control the life cycle of the object referred to, it points to an object managed by a shared_ptr. Binding a weak_ptr to a shared_ptr does not change the shared_ptr counter. Once the last shared_ptr pointing to the object is destroyed, the object is released, even if there is a weak_ptr pointing to the object. First, let's start with a table where the nagging weak_ptr operation function describes weak_ptr w empty weak_ptr, which can point to objects of type T*. Weak_ptr w (sp) and shared_sp sp point to the weak_ptr of the same object. T must be able to be converted to the type referred to by sp. W = pp can be a shared_ptr or a weak_ptr. After assignment, w points to the object referred to by p. W.reset () sets w to empty w.use_count () the number of shared_ptr shared with w object w.expired () returns true if w.use_count () is 0, otherwise returns falsew.lock () if expired () is true, returns an empty shared_ptr; otherwise returns a shared_ptr pointing to the object referred to by w. The small example indexing code block function describes that test1weak_ptr does not increase the reference count test2weak_ptr does not have-> and * operation test3lock uses test4 circular references, resulting in that even smart pointers cannot free memory. Use weak_ptr to solve the problem that memory cannot be freed due to circular references # include # include # include using namespace std; class Test {public: Test (int d = 0): data (d) {cout

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

Internet Technology

Wechat

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

12
Report