本文介绍基于std::shared_ptr自定义allocator引入内存池的方法。 尝试重写new和delete运算符 项目中大量使用std::shared_ptr且与多个模块耦合, 如果直接将std::shared_ptr重构为手动管理裸指针的实现,改动量太大,而且可能会带来不可预料的问题。于是尝试了重写new和delete运算符并添加了打印,发现std::shared_ptr的创建...
项目中大量使用std::shared_ptr且与多个模块耦合, 如果直接将std::shared_ptr重构为手动管理裸指针的实现,改动量太大,而且可能会带来不可预料的问题。于是尝试了重写new和delete运算符来手动管理内存,并添加了打印,发现std::shared_ptr的创建并不会直接调用new和delete, 原因在于std::shared_ptr有自己的内存分配机制。
三种智能指针 shared_ptr,unique_ptr,weak_ptr; 将shared_ptr存放在一个容器中,不再需要它的时候,要erase掉。 allocator负责封装堆内存管理的对象,它们在整个标准库中使用,特别是STL容器使用它们来管理容器内部的所有内存分配,大部份情况下,程序员不用理会,标准容器使用默认的分配器称为std :: allocator。 shared_p...
using _Ptr = typename unique_ptr<_Tp, _Del>::pointer; using _Del2 = typename conditional<is_reference<_Del>::value, reference_wrapper<typename remove_reference<_Del>::type>, _Del>::type; using _Sp_cd_type = _Sp_counted_deleter<_Ptr, _Del2, allocator<void>, _Lp>; using _Alloc =...
// allocate_shared example#include<iostream>#include<memory>intmain(){std::allocator<int>alloc;// the default allocator for intstd::default_delete<int>del;// the default deleter for intstd::shared_ptr<int>foo=std::allocate_shared<int>(alloc,10);auto bar=std::allocate_shared<int>(alloc,...
deleter放在control block里,只有在所有weak,strong计数清零后才会析构,如果deleter里包含了别的资源,会有潜在泄漏可能。还有shared_from_this没有allocator参数(以前是这样)。多线程析构在哪个线程不确定,这导致allocator必须线程安全。智能指针有shared_ptr和unique_ptr两个,week_ptr不拥有资源,配合shared_ptr防止...
具体来说,shared_ptr<Foo> 包含两个成员,一个是指向 Foo 的指针 ptr,另一个是 ref_count 指针(其类型不一定是原始指针,有可能是 class 类型,但不影响这里的讨论),指向堆上的 ref_count 对象。ref_count 对象有多个成员,具体的数据结构如图 1 所示,其中 deleter 和 allocator 是可选的。
2. sp_counted_impl_pd:用户指定了Deleter,没有指定Allocator 3. sp_counted_impl_pda:用户指定了Deleter和 Allocator 创建指针P的第一个shared_ptr对象的时候,子对象shared_count同时被建立, shared_count根据用户提供的参数选择创建一个特定的sp_counted_base派生类对象X。之后创建的所有管理P的shared_ptr对象都指...
std::shared_ptr<int> p3 (new int); std::shared_ptr<int> p4 (new int, std::default_delete<int>()); std::shared_ptr<int> p5 (new int, [](int* p){delete p;}, std::allocator<int>()); std::shared_ptr<int> p6 (p5); ...
1. sp_counted_impl_p:用户没有指定Deleter和Allocator 2. sp_counted_impl_pd:用户指定了Deleter,没有指定Allocator 3. sp_counted_impl_pda:用户指定了Deleter和 Allocator 创建指针P的第一个shared_ptr对象的时候,子对象shared_count同时被建立, shared_count根据用户提供的参数选择创建一个特定的sp_counted_base...