這裏是另一種解決方案(除了小李的):
#include <type_traits>
#include <utility>
#include <memory>
template <class T, class ...Args>
typename std::enable_if
<
!std::is_array<T>::value,
std::unique_ptr<T>
>::type
make_unique(Args&& ...args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
template <class T>
typename std::enable_if
<
std::is_array<T>::value,
std::unique_ptr<T>
>::type
make_unique(std::size_t n)
{
typedef typename std::remove_extent<T>::type RT;
return std::unique_ptr<T>(new RT[n]);
}
int main()
{
auto p1 = make_unique<int>(3);
auto p2 = make_unique<int[]>(3);
}
注:
- 新的T [N]應該只是默認構造n T's。
所以make_unique(n)應該默認構造n T's。
- 像這樣的問題有助於make_unique沒有在C++ 11中提出。另一個問題是:我們是否處理自定義刪除者?
這些都不是無法回答的問題。但他們是尚未完全解答的問題。
...但這些問題已經(部分)在C++ 14中得到解答,並且make_unique現在是[更豐富](http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique)。 – einpoklum 2016-11-07 15:21:59
@einpoklum:正確。注意Q/A上的日期。 – 2016-11-07 20:18:05