提问人:Peter Fletcher 提问时间:9/19/2023 最后编辑:Remy LebeauPeter Fletcher 更新时间:9/19/2023 访问量:61
为什么 std::make_shared<T> 不是 std::shared_ptr<T> 的静态函数,即 std::shared_ptr<T>::make?
Why is std::make_shared<T> not a static function of std::shared_ptr<T>, i.e. std::shared_ptr<T>::make?
问:
这是一个关于理解设计决策的问题,而不是对错误或缺陷的抱怨。
在 C++ 标准库中,创建共享指针及其对象的函数是一个直函数,
template< class T, class... Args> std::shared_ptr<T> make_shared( Args&&... args );
为什么这个函数不是 的函数,像这样:static
shared_ptr<T>
template <class... Args> std::shared_ptr<T>::make(Args&&... args);
这将使命名空间更整洁一些,并且还允许如下内容:std::
using shared_vector = std::shared_ptr<std::vector<int>>;
shared_vector a = shared_vector::make(7);
答:
5赞
user17732522
9/19/2023
#1
文档 N2351 的提案中给出的唯一理由是,它使得以非侵入性地将功能添加到任何已经存在的 实现 中成为可能。std::make_shared
shared_ptr
std::make_shared
在标准草案之后被添加到标准草案中,并且之前有过实现,例如在 boost 中。std::shared_ptr
shared_ptr
评论
std::unique_ptr
也没有这个。