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 2 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
1 change: 1 addition & 0 deletions src/bsoncxx/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ else()
endif()
if(ENABLE_TESTS)
target_compile_definitions(bsoncxx_testing PUBLIC BSONCXX_TESTING)
add_library(bsoncxx::testing ALIAS bsoncxx_testing)
endif()

set (libdir "\${prefix}/${CMAKE_INSTALL_LIBDIR}")
Expand Down
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 value-initializable
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* - T must be value-initializable
* - 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>
4 changes: 2 additions & 2 deletions src/bsoncxx/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ endif()
# Allow `#include <third_party/catch/include/...>`
include_directories(${THIRD_PARTY_SOURCE_DIR}/..)

file (GLOB src_bsoncxx_test_DIST_cpps RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp)
file (GLOB src_bsoncxx_test_DIST_cpps CONFIGURE_DEPENDS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp)

add_executable(test_bson
${THIRD_PARTY_SOURCE_DIR}/catch/main.cpp
${src_bsoncxx_test_DIST_cpps}
)

target_link_libraries(test_bson bsoncxx_testing ${libbson_target})
target_link_libraries(test_bson PRIVATE bsoncxx::testing ${libbson_target})
target_include_directories(test_bson PRIVATE ${libbson_include_directories})
target_compile_definitions(test_bson PRIVATE ${libbson_definitions})

Expand Down
43 changes: 43 additions & 0 deletions src/bsoncxx/test/make_unique.test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#include <algorithm>
#include <cstdint>
#include <new>

#include <bsoncxx/stdx/make_unique.hpp>
#include <bsoncxx/test_util/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);
CHECKED_IF(ptr) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
CHECKED_IF(ptr) {
CHECK(ptr);
CHECKED_IF(ptr) {

Suggest checking ptr since CHECKED_IF only enters block if the expression evaluates to true.

Suggestion applies to other CHECKED_IF statements.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was going to say that this is desired behavior, but I double-checked the docs and

CHECKED_X macros were changed to not count as failure in Catch2 3.0.1.

😐

As someone that has used these macros heavily across dozens projects for several years and seems to have missed this release note, this is an extremely breaking change from Catch2, and there doesn't appear to be a viable alternative?? It seems that I have a lot of tests to go and fix now. I need to go lay down.

CHECK(*ptr == 12);
}

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

TEST_CASE("Create a unique_ptr<T[]>") {
const unsigned length = 12;
auto ptr = bsoncxx::stdx::make_unique<int[]>(length);
CHECKED_IF(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
3 changes: 2 additions & 1 deletion src/mongocxx/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,9 @@ else()
endif()
endif()
if(ENABLE_TESTS)
target_link_libraries(mongocxx_mocked PUBLIC bsoncxx_testing)
target_link_libraries(mongocxx_mocked PUBLIC bsoncxx::testing)
target_compile_definitions(mongocxx_mocked PUBLIC MONGOCXX_TESTING)
add_library(mongocxx::mocked ALIAS mongocxx_mocked)
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
target_compile_options(mongocxx_mocked PRIVATE /bigobj)
endif()
Expand Down
33 changes: 19 additions & 14 deletions src/mongocxx/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ add_executable(test_driver

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
target_link_libraries(test_driver Threads::Threads)
target_link_libraries(test_driver PRIVATE Threads::Threads)

add_executable(test_logging
${THIRD_PARTY_SOURCE_DIR}/catch/main.cpp
Expand Down Expand Up @@ -186,19 +186,24 @@ add_executable(test_versioned_api
${spec_test_common}
)

target_link_libraries(test_driver mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_logging mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_instance mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_client_side_encryption_specs mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_crud_specs mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_gridfs_specs mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_command_monitoring_specs mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_transactions_specs mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_retryable_reads_specs mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_read_write_concern_specs mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_mongohouse_specs mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_unified_format_spec mongocxx_mocked ${libmongoc_target})
target_link_libraries(test_versioned_api mongocxx_mocked ${libmongoc_target})
set_property(
TARGET
test_driver
test_logging
test_instance
test_client_side_encryption_specs
test_crud_specs
test_gridfs_specs
test_command_monitoring_specs
test_transactions_specs
test_retryable_reads_specs
test_read_write_concern_specs
test_mongohouse_specs
test_unified_format_spec
test_versioned_api
APPEND PROPERTY LINK_LIBRARIES
mongocxx::mocked ${libmongoc_target}
)

target_include_directories(test_driver PRIVATE ${libmongoc_include_directories})
target_include_directories(test_logging PRIVATE ${libmongoc_include_directories})
Expand Down