命名空间
变体
操作

std::shared_ptr 的推导指引

来自 cppreference.cn
< cpp‎ | memory‎ | shared ptr
 
 
内存管理库
(仅供演示*)
未初始化内存算法
(C++17)
(C++17)
(C++17)
受约束的未初始化
内存算法
C 库

分配器
内存资源
垃圾回收支持
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
(C++11)(直到 C++23)
未初始化存储
(直到 C++20*)
(直到 C++20*)
显式生命周期管理
 
 
定义于头文件 <memory>
template< class T >
shared_ptr( std::weak_ptr<T> ) -> shared_ptr<T>;
(1) (自 C++17 起)
template< class T, class D >
shared_ptr( std::unique_ptr<T, D> ) -> shared_ptr<T>;
(2) (自 C++17 起)

std::shared_ptr 提供了这些 推导指引,以处理隐式推导指引遗漏的边缘情况。

注意,不存在从指针类型的类模板实参推导,因为不可能区分从数组和非数组形式的 new 获得的指针。

[编辑] 示例

#include <memory>
 
int main()
{
    auto p = std::make_shared<int>(42);
    std::weak_ptr w{p};    // explicit deduction guide is used in this case
    std::shared_ptr p2{w}; // explicit deduction guide is used in this case
}