【C++】make_unique的实现


namespace memory_internal {

template <typename T>
struct MakeUniqueResult {
    using scalar = std::unique_ptr<T>;
};
template <typename T>
struct MakeUniqueResult<T[]>
{
    using array = std::unique_ptr<T[]>;
};
template <typename T, size_t N>
struct MakeUniqueResult<T[N]> {
    using invalid = void;
};
} // namespace memory_internal

// overload for non-array types.
template <typename T, typename... Args>
typename memory_internal::MakeUniqueResult<T>::scalar make_unique(
    Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

// `make_unique` overload for an array T[] of unknown bounds.
// The array allocation needs to use the `new T[size]` form and cannot take
// element constructor arguments. The `std::unique_ptr` will manage destructing
// these array elements.
template <typename T>
typename memory_internal::MakeUniqueResult<T>::array make_unique(size_t n) {
    return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
}

// `make_unique` overload for an array T[N] of known bounds.
// This construction will be rejected.
template <typename T, typename... Args>
typename memory_internal::MakeUniqueResult<T>::invalid make_unique(
    Args&&... /* args */) = delete;

make_unique实现数组的时候需要知道大小。。

为啥呢??

发布了423 篇原创文章 · 获赞 14 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/LU_ZHAO/article/details/105477955