当前位置:网站首页>Smart pointer (shared_ptr, unique_ptr, weak_ptr)
Smart pointer (shared_ptr, unique_ptr, weak_ptr)
2022-07-27 11:22:00 【Hungry Taibai Xingjun】
#include <iostream>
#include <memory>
int main() {
// ( One )shared_ptr
// 1. initialization . Smart pointer is a template class , You can specify the type , The passed in pointer is initialized by the constructor . You can also use make_shared Function initialization .
// 2. Cannot assign a pointer directly to a smart pointer , One is class , One is the pointer . for example std::shared_ptr<int> p4 = new int(1); It's wrong to write it in Chinese
// 3. Copy and assign . Copy increases the reference count of an object 1, Assignment decrements the reference count of the original object 1, When count is 0 when , Automatically free up memory . The reference count of the object pointed to later is added 1, Point to the next object .
// 4. get Function to get the original pointer
// 5. Be careful not to initialize more than one with a single raw pointer shared_ptr, Otherwise, the same memory will be released twice
// 6. Be careful to avoid circular references ,shared_ptr One of the biggest pitfalls of is circular references , loop , Circular references can cause heap memory not to be released properly , Cause memory leaks . The circular reference is in weak_ptr Described in the .
int a = 10;
std::shared_ptr<int> sptr(new int(10));
std::shared_ptr<int> ptra = std::make_shared<int>(a);
std::shared_ptr<int> ptra2(ptra); // copy
std::cout << ptra.use_count() << std::endl;//2
int b = 20;
int *pb = &a;
// std::shared_ptr<int> ptrb = pb; // A pointer cannot be directly assigned to a smart pointer , One is class , One is the pointer
std::shared_ptr<int> ptrb = std::make_shared<int>(b);
ptra2 = ptrb; // assign,ptra2 It's a copy of ptra, take ptrb Assign a value to ptra2 after ,ptra Reference count of -1
pb = ptrb.get();
std::cout << ptra.use_count() << std::endl;//1
std::cout << ptrb.use_count() << std::endl;//2
// ( Two )unique_ptr
// 1. There can only be one... At a time unique_ptr Point to the given object
// 2. unique_ptr The life cycle of the pointer itself : from unique_ptr When the pointer is created , Until you leave the scope .
// 3. When out of scope , If it points to the object , Destroy the object it refers to ( By default delete The operator , The user can specify other actions ).
// 4. unique_ptr The relationship between a pointer and its object : Within the life cycle of the smart pointer , You can change the object the smart pointer refers to , For example, when creating an intelligent pointer, it is specified by the constructor 、 adopt reset Method reassignment 、 adopt release Method to release ownership 、 Transfer ownership through mobile semantics .
{
std::unique_ptr<int> uptr(new int(10)); // Binding dynamic objects
// std::unique_ptr<int> uptr2(uptr); // Can't copy
// std::unique_ptr<int> uptr2 = uptr; // Can't assign a value
std::unique_ptr<int> uptr2 = std::move(uptr); // Conversion ownership
uptr2.release();
}
// exceed uptr Scope of action , Memory free
// ( 3、 ... and )weak_ptr
// 1. In order to cooperate shared_ptr Smart pointer just introduced , It doesn't have the behavior of ordinary pointers , No overloading operator* and ->, Its greatest function is to help shared_ptr Work , Observe the use of resources like a bystander .
// 2. weak_ptr Can be from a shared_ptr Or another weak_ptr Object construction , Get the right to observe resources . but weak_ptr No shared resources , Its construction does not cause the pointer reference count to increase .
// 3.
{
std::shared_ptr<int> sh_ptr = std::make_shared<int>(10);
std::cout << sh_ptr.use_count() << std::endl;//1
std::weak_ptr<int> wp(sh_ptr); // Use shared_ptr structure
std::cout << wp.use_count() << std::endl;//1
if (!wp.expired())// Member functions expired() The function of is equivalent to use_count()==0
{
// weak_ptr You can use a very important member function lock() From the observed shared_ptr Get a usable shared_ptr object , To operate resources .
// But when expired()==true When ,lock() Function will return a null pointer shared_ptr.
std::shared_ptr<int> sh_ptr2 = wp.lock(); // get sh_ptr
*sh_ptr = 100;
std::cout << wp.use_count() << std::endl; //2
}
}
// Memory free
return 0;
}
边栏推荐
- 49 letter ectopic grouping and 242 effective letter ectopic words
- 7 row K with the weakest combat effectiveness in the matrix
- Why is the data service API the standard configuration of the data midrange when we take the last mile of the data midrange?
- Internal and external troubles of digital collection NFT "boring ape" bayc
- Luogu p1896 non aggression
- 349 sum of intersection of two arrays and 01
- 背包模型 AcWing 1022. 宠物小精灵之收服
- Win10 vscode code code format setting and remote breakpoint debugging
- Redis+caffeine two-level cache enables smooth access speed
- Properties file
猜你喜欢

Opengauss kernel analysis - statistics and row count estimation

KEPServer配置

2022 Niuke multi school (3) j.journey

Asustek unparalleled, this may be the best affordable high brush thin notebook on the screen

Find the combinatorial number acwing 889. 01 sequence satisfying the condition

求组合数 AcWing 888. 求组合数 IV
![Take you hand-in-hand to develop a complete classic game [Tetris] from scratch, with less than 200 lines of logic.](/img/7f/f42f9267cdff35522c260ef073bab9.png)
Take you hand-in-hand to develop a complete classic game [Tetris] from scratch, with less than 200 lines of logic.

Instructions for mock platform

博弈论 AcWing 893. 集合-Nim游戏

求组合数 AcWing 885. 求组合数 I
随机推荐
Digital triangle model acwing 1018. Minimum toll
Wechat push - template message parameter configuration
TensorFlow张量运算函数集
Backpack model acwing 1022. Collection of pet elves
Game theory acwing 892. Step Nim game
Taishan Office Technology Lecture: scaling and opening files
Error while unzipping file in win10: unable to create symbolic link. You may need to run WinRAR with administrator privileges. The client does not have the required privileges
Based on the open source stream batch integrated data synchronization engine Chunjun data restore DDL parsing module actual combat sharing
SQL Server2000 database error
Game theory acwing 894. Split Nim game
IO stream_ Overview and explanation of data input and output flow
数字三角形模型 AcWing 1018. 最低通行费
When std:: bind meets this
Data assets are king. How to analyze the relationship between enterprise digital transformation and data asset management?
Redis+caffeine two-level cache enables smooth access speed
【FPGA教程案例40】通信案例10——基于FPGA的简易OFDM系统verilog实现
力扣——10. 正则表达式匹配
Where is the big data open source project, one-stop fully automated full life cycle operation and maintenance steward Chengying (background)?
FAQs of "relay chain" and "dot" in Poka ecosystem
数字三角形模型 AcWing 1015. 摘花生