std::shared_ptr 的推导指引

定义于头文件 <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};    // 用于此情况的显式推导指引
    std::shared_ptr p2{w}; // 用于此情况的显式推导指引
}


版本历史

  • (当前 | 先前) 2017年8月20日 (日) 23:56Fruderica讨论 | 贡献. . (919字节) (+919). . (以“{{title|{{tt|std::shared_ptr}} 的推导指引}} {{cpp/memory/shared_ptr/navbar}} {{dcl begin}} {{dcl header|memory}} {{dcl | num=1 | since=c++17 | template <class T...”为内容创建页面)