对于新的操作符,我们有std::nothrow版本:
std::unique_ptr<T> p = new(std::nothrow) T();对于std::make_shared还是std::make_unique,我们有这样的东西吗?
发布于 2019-07-18 10:31:07
不,我们没有。通过查看make_unique和make_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 Jul 18 '19 10:46
https://stackoverflow.com/questions/57092289
复制相似问题