std :: make_shared和std :: make_unique是否具有“ nothrow”版本?

时间:2019-07-18 10:20:07

标签: c++ new-operator c++-standard-library nothrow

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

std::unique_ptr<T> p = new(std::nothrow) T();

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

1 个答案:

答案 0 :(得分:8)

不,我们没有。浏览make_uniquemake_shared的cppreference页面,我们发现每个版本都使用默认的new重载。

实现这样的过程并不难,

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   19年7月18日在10:46

相关问题