在自定义分配器中,一般不需要手动实现construct和destroy,因为标准库中的std::allocator_traits会处理这些工作。std::allocator_traits默认会使用placement new来调用对象的构造函数,并调用对象的析构函数。 相当于在CustomAllocator中增加以下函数: template<typenameU,typename... Args>voidconstruct(U* p, Args&&... ...
使用std::allocate_shared 接下来就可以使用std::allocate_shared了 ,需传入自定义分配器allocator对象和类的构造函数参数列表。仿照std::make_shared的实现,基于可变长参数模板做了一层函数封装: template<typenameT,typename...Args>std::shared_ptr<T>AllocateShared(Args&&...args){returnstd::allocate_shared<T...
delete [] p;//当销毁一个数组动态对象时需要加上[] 3.allocator的使用,头文件:#include <memory> (1)使用new创建动态对象的时候,必须在分配内存的时候就对其进行初始化,就是在new的时候就会调用构造函数,同样delete的时候就会调用析构函数。 (2)如果我们希望创建动态对象,并且将其为这个对象分配内存和初始化分...
AI代码解释 // 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<i...
九、小结 本文总结了写一个简单shared_ptr的思路,但无论如何这只是一个toy,没有考虑循环引用的问题、不支持自定义allocator和deleter、也没有考虑performance等等,实际上要写一个兼顾性能、可靠性、易用性、跨平台等特性的工业级智能指针,会比这复杂的多的多,标准库的智能指针实现就是一个很好的例子。
具体来说,shared_ptr<Foo> 包含两个成员,一个是指向 Foo 的指针 ptr,另一个是 ref_count 指针(其类型不一定是原始指针,有可能是 class 类型,但不影响这里的讨论),指向堆上的 ref_count 对象。ref_count 对象有多个成员,具体的数据结构如图 1 所示,其中 deleter 和 allocator 是可选的。
3. sp_counted_impl_pda:用户指定了Deleter和 Allocator 创建指针P的第一个shared_ptr对象的时候,子对象shared_count同时被建立, shared_count根据用户提供的参数选择创建一个特定的sp_counted_base派生类对象X。之后创建的所有管理P的shared_ptr对象都指向了这个独一无二的X。
Allocator 分配器的类型。 deleter 删除器。 alloc 分配器。 sp 要复制的智能指针。 wp 弱指针。 ap 要复制的自动指针。 备注 每个构造函数都将构造一个对象,该对象拥有由操作数序列命名的资源。 如果 wp.expired(),构造函数 shared_ptr(const weak_ptr<Other>& wp) 引发类型 bad_weak_ptr 的异常对象。 示...
std::shared_ptr<int> p5 (new int, [](int* p){delete p;}, std::allocator<int>()); std::shared_ptr<int> p6 (p5); std::shared_ptr<int> p7 (std::move(p6)); std::shared_ptr<int> p8 (std::unique_ptr<int>(new int)); ...
deleter放在control block里,只有在所有weak,strong计数清零后才会析构,如果deleter里包含了别的资源,会有潜在泄漏可能。还有shared_from_this没有allocator参数(以前是这样)。多线程析构在哪个线程不确定,这导致allocator必须线程安全。智能指针有shared_ptr和unique_ptr两个,week_ptr不拥有资源,配合shared_ptr防止...