ideas icon indicating copy to clipboard operation
ideas copied to clipboard

Добавить std::make_unique_nothrow() и std::make_shared_nothrow() функции

Open klappdev opened this issue 2 years ago • 0 comments

Использование std::make_unique() и std::make_shared() может привести к киданию исключение std::bad_alloc, если памяти не достаточно. В таких случаях, необходимо использовать оператор new с std::nothrow.

#include <memory>

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

Функции std::make_shared() и std::make_unique() более эффективны и могут предотвратить двойное выделения памяти. Предлагается добавить std::make_unique_nothrow() и std::make_shared_nothrow() функции, которые можно реализовано следующим образом.

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)...));
}

В библиотеке boost уже реализована подобные функции https://www.boost.org/doc/libs/1_63_0/boost/move/make_unique.hpp

klappdev avatar Aug 24 '23 13:08 klappdev