首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >std::make_shared和std::make_unique是否有"nothrow“版本?

std::make_shared和std::make_unique是否有"nothrow“版本?
EN

Stack Overflow用户
提问于 2019-07-18 10:20:07
回答 1查看 2.5K关注 0票数 14

对于新的操作符,我们有std::nothrow版本:

代码语言:javascript
复制
std::unique_ptr<T> p = new(std::nothrow) T();

对于std::make_shared还是std::make_unique,我们有这样的东西吗?

EN

回答 1

Stack Overflow用户

发布于 2019-07-18 10:31:07

不,我们没有。通过查看make_uniquemake_shared的cppreference页面,我们可以看到每个版本都使用默认的new重载。

不过,要实现这样的一种方法并不困难:

代码语言:javascript
复制
template <class T, class... Args>
std::unique_ptr<T> make_unique_nothrow(Args&&... args)
    noexcept(noexcept(T(std::forward<Args>(args)...)))
{
    return std::unique_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...));
}

template <class T, class... Args>
std::shared_ptr<T> make_shared_nothrow(Args&&... args)
    noexcept(noexcept(T(std::forward<Args>(args)...)))
{
    return std::shared_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...));
}

(请注意,这个版本的make_shared_nothrow并不像make_shared那样避免双重分配。)C++20为make_unique增加了许多新的重载,但它们可以以类似的方式实现。另外,根据comment

使用此版本时,不要忘记在使用指针之前检查它。- Superlokkus Jul 18 '19 10:46

票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57092289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档