Skip to content

[CXX-2625] Bring our own make_unique #1028

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 109 additions & 37 deletions src/bsoncxx/include/bsoncxx/v_noabi/bsoncxx/stdx/make_unique.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,52 +14,124 @@

#pragma once

#include <bsoncxx/config/prelude.hpp>

#if defined(BSONCXX_POLY_USE_MNMLSTC)

#include <core/memory.hpp>

namespace bsoncxx {
BSONCXX_INLINE_NAMESPACE_BEGIN
namespace stdx {

using ::core::make_unique;

} // namespace stdx
BSONCXX_INLINE_NAMESPACE_END
} // namespace bsoncxx

#elif defined(BSONCXX_POLY_USE_BOOST)

#include <boost/smart_ptr/make_unique.hpp>

namespace bsoncxx {
BSONCXX_INLINE_NAMESPACE_BEGIN
namespace stdx {

using ::boost::make_unique;

} // namespace stdx
BSONCXX_INLINE_NAMESPACE_END
} // namespace bsoncxx

#elif __cplusplus >= 201402L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)

#include <cstddef>
#include <memory>
#include <type_traits>
#include <utility>

#include <bsoncxx/config/prelude.hpp>

namespace bsoncxx {
BSONCXX_INLINE_NAMESPACE_BEGIN
namespace stdx {

using ::std::make_unique;
namespace detail {

// Switch backend of make_unique by the type we are creating.
// It would be easier to 'if constexpr' on whether we are an array and whether to direct-init or
// value-init, but we don't have if-constexpr and we need it to guard against an uterance of a
// possibly-illegal 'new' expression.
template <typename T>
struct make_unique_impl {
// For make_unique:
template <typename... Args,
// Guard on constructible-from:
typename = decltype(new T(std::declval<Args>()...))>
static std::unique_ptr<T> make(std::true_type /* direct-init */, Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

// For make_unique_for_overwrite:
template <typename U = T,
// Guard on whether T is value-initializable:
// (Hide behind a deduced 'U' to defer the evaluation of
// this default template argument until overload resolution)
typename = decltype(new U)>
static std::unique_ptr<T> make(std::false_type /* value-init */) {
return std::unique_ptr<T>(new T);
}
};

// For unbounded arrays:
template <typename Elem>
struct make_unique_impl<Elem[]> {
template <typename ShouldDirectInit,
// Guard on whether the new-expression will be legal:
typename = decltype(new Elem[std::declval<std::size_t>()])>
static std::unique_ptr<Elem[]> make(ShouldDirectInit, std::size_t count) {
// These can share a function via a plain if, because both new expressions
// must be semantically valid
if (ShouldDirectInit()) {
return std::unique_ptr<Elem[]>(new Elem[count]());
} else {
return std::unique_ptr<Elem[]>(new Elem[count]);
}
}
};

// Bounded arrays are disallowed:
template <typename Elem, std::size_t N>
struct make_unique_impl<Elem[N]> {};

// References are nonsense:
template <typename T>
struct make_unique_impl<T&> {};

// References are nonsense:
template <typename T>
struct make_unique_impl<T&&> {};

} // namespace detail

/**
* @brief Create a new std::unique_ptr that points-to the given type, direct-initialized based on
* the given arguments.
*
* @tparam T Any non-array object type or any array of unknown bound.
* @param args If T is a non-array object type, these are the constructor arguments used to
* direct-initialize the object. If T is an array of unknown bound, then the sole argument must be a
* single std::size_t that specifies the number of objects to allocate in the array.
*
* Requires:
* - If T is an array of unknown bounds, then args... must be a single size_t and the element type
* of T must be value-initializable.
* - Otherwise, if T is a non-array object type, then T must be direct-initializable with arguments
* `args...`
* - Otherwise, this function is excluded from overload resolution.
*/
template <typename T,
typename... Args,
typename Impl = detail::make_unique_impl<T>,
typename = decltype(Impl::make(std::true_type{}, std::declval<Args>()...))>
std::unique_ptr<T> make_unique(Args&&... args) {
return Impl::make(std::true_type{}, std::forward<Args>(args)...);
}

/**
* @brief Create a new std::unique_ptr that points-to a default-initialized instance of the given
* type.
*
* @tparam T A non-array object type or an array of unknown bound
* @param args If T is an object type, then args... must no arguments are allowed.
* If T is an array of unknown bound, then args... must be a single size_t specifying
* the length of the array to allocate.
*
* Requires:
* - T must be default-initializable
* - If T is an array of unknown bounds, then args... must be a single size_t
* - Otherwise, if T is a non-array object type, args... must be empty
* - Otherwise, this function is excluded from overload resolution
*/
template <typename T,
typename... Args,
typename Impl = detail::make_unique_impl<T>,
typename = decltype(Impl::make(std::false_type{}, std::declval<Args>()...))>
std::unique_ptr<T> make_unique_for_overwrite(Args&&... args) {
return Impl::make(std::false_type{}, std::forward<Args>(args)...);
}

} // namespace stdx
BSONCXX_INLINE_NAMESPACE_END
} // namespace bsoncxx

#else
#error "Cannot find a valid polyfill for make_unique"
#endif

#include <bsoncxx/config/postlude.hpp>
2 changes: 2 additions & 0 deletions src/bsoncxx/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ add_executable(test_bson
json.cpp
oid.cpp
view_or_value.cpp
make_unique.test.cpp
)

# Common target properties for test executables.
Expand Down Expand Up @@ -72,4 +73,5 @@ set_dist_list(src_bsoncxx_test_DIST
oid.cpp
to_string.hh
view_or_value.cpp
make_unique.test.cpp
)
40 changes: 40 additions & 0 deletions src/bsoncxx/test/make_unique.test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#include <algorithm>
#include <cstdint>
#include <new>

#include <bsoncxx/stdx/make_unique.hpp>
#include <bsoncxx/test/catch.hh>

namespace {

struct something {
something(int val) : value(val) {}
int value;
};

TEST_CASE("Create a unique_ptr") {
auto ptr = bsoncxx::stdx::make_unique<int>(12);
REQUIRE(ptr);
CHECK(*ptr == 12);

auto thing = bsoncxx::stdx::make_unique<something>(5);
REQUIRE(thing);
CHECK(thing->value == 5);
}

TEST_CASE("Create a unique_ptr<T[]>") {
const unsigned length = 12;
auto ptr = bsoncxx::stdx::make_unique<int[]>(length);
REQUIRE(ptr);
// All elements are direct-initialized, which produces '0' for `int`
CHECK(ptr[0] == 0);
auto res = std::equal_range(ptr.get(), ptr.get() + length, 0);
CHECK(res.first == ptr.get());
CHECK(res.second == (ptr.get() + length));

ptr = bsoncxx::stdx::make_unique_for_overwrite<int[]>(length);
std::fill_n(ptr.get(), length, 42);
CHECK(std::all_of(ptr.get(), ptr.get() + length, [](int n) { return n == 42; }));
}

} // namespace