unique_ptr 与 shared_ptr 的 deleter
使用std::unique_ptr<>
定义(声明)一个对象的时候,需要知道这个对象的Deleter
,std::unique_ptr
的原型如下:
template<
class T,
class Deleter = std::default_delete<T>
> class unique_ptr;
如果在定义/声明一个unique_ptr对象的时候,这个对象是imcomplete type
,因为default deleter的实现中需要使用sizeof(object),不能确定对象的大小,所以编译报错:
`error: invalid application of 'sizeof' to an incomplete type 'student'`
使用std::shared_ptr<>
,shared_ptr
里面的数据结构跟unique_ptr
不一样,shared_ptr
里面保存的是对象指针,以及一个指向control block
的指针,所以在申明/定义的时候,可以不需要知道对象的完整类型。control block
里面保存的是对象的allocator
,deleter
,atomic reference
等成员。
源码如下:
```plaintext
costexpr __shared_ptr()
: _M_ptr(0), _M_refcount() // never throws
{ }
template<typename _Tp1>
explicit __shared_ptr(_Tp1* __p)
: _M_ptr(__p), _M_refcount(__p) {
__glibcxx_function_requires(_ConvertibleConcept<_Tp1*, _Tp*>)
static_assert( sizeof(_Tp1) > 0, "incomplete type" );
__enable_shared_from_this_helper(_M_refcount, __p, __p);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构