Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use weak_ptr in C language Intelligent pointer

Shulou Source: shulou.com Published: 2022-06-03 04:37:18 09月12日 Update

This article mainly explains the "C language smart pointer how to use weak_ptr", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "C language smart pointer how to use weak_ptr" bar!

Preface

Weak_ptr, a pointer born with the appearance of a "little brother", is also a standard library introduced in Cellular 11. Its appearance is entirely to make up for the inherent defects of its boss, shared _ ptr. In fact, compared with the previous generation of smart pointer auto_ptr, the new boss shared_ptr can be said to be almost perfect, but it is realized through reference counting, although it solves the problem of pointer monopoly, but also leads to the problem of reference ring. This kind of problem can't be solved on its own, so shared_ptr and weak_ptr were introduced into the standard library to solve the problem of circular reference.

Weak_ptr itself is also a template class, but it cannot be used directly to define an object with a smart pointer. It can only be used with shared_ptr. The object of shared_ptr can be assigned to weak_ptr, and this does not change the value of the reference count. Look at the code of weak_ptr found that it mainly has lock, swap, reset, expired, operator=, use_count several functions, compared with shared_ptr more lock, expired function, but less get function, and even operator* and operator- > are not, the number of functions available is pitiful, the following through some examples to understand the specific use of weak_ptr.

Use environment

1.VS2015 + Windows7 (should be the Clear11 standard)

two。 Header file # include

3. Namespace using namespace std

Testing process

1.weak_ptr solves the problem of shared_ptr circular reference

Define two classes, and each class contains a smart pointer to the other's type as a member variable, then create an object, check the reference count and exit after setting it up, and take a look at the test results:

Class CB;class CA {public: CA () {cout

Tags: Object function output pointer problem point intelligence type test variable result compilation that is language only member time error loop two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia macOS Shulou Information MySQL Redmi