cpp-ru / ideas

Идеи по улучшению языка C++ для обсуждения
https://cpp-ru.github.io/proposals
Creative Commons Zero v1.0 Universal
89 stars 0 forks source link

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

Open klappdev opened 10 months ago

klappdev commented 10 months ago

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

#include <memory>

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

Функции _std::makeshared() и _std::makeunique() более эффективны и могут предотвратить двойное выделения памяти. Предлагается добавить _std::make_uniquenothrow() и _std::make_sharednothrow() функции, которые можно реализовано следующим образом.

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