2012-04-14 27 views
11

作爲後續到this後我不知道如何實現make_unique玩分配函數臨時緩衝區數組,如下面的代碼。C++數組和make_unique

f() 
{ 
    auto buf = new int[n]; // temporary buffer 
    // use buf ... 
    delete [] buf; 
} 

這能與一些呼叫make_unique更換,將刪除情況[] -version被繼續使用?

回答

16

這裏是另一種解決方案(除了小李的):

#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); 
} 

注:

  1. 新的T [N]應該只是默認構造n T's。

所以make_unique(n)應該默認構造n T's。

  1. 像這樣的問題有助於make_unique沒有在C++ 11中提出。另一個問題是:我們是否處理自定義刪除者?

這些都不是無法回答的問題。但他們是尚未完全解答的問題。

+0

...但這些問題已經(部分)在C++ 14中得到解答,並且make_unique現在是[更豐富](http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique)。 – einpoklum 2016-11-07 15:21:59

+0

@einpoklum:正確。注意Q/A上的日期。 – 2016-11-07 20:18:05

4

我得到了它,此代碼的工作:

#include <memory> 
#include <utility> 

namespace Aux { 
    template<typename Ty> 
    struct MakeUnique { 
     template<typename ...Args> 
     static std::unique_ptr<Ty> make(Args &&...args) { 
      return std::unique_ptr<Ty>(new Ty(std::forward<Args>(args)...)); 
     } 
    }; 

    template<typename Ty> 
    struct MakeUnique<Ty []> { 
     template<typename ...Args> 
     static std::unique_ptr<Ty []> make(Args &&...args) { 
      return std::unique_ptr<Ty []>(new Ty[sizeof...(args)]{std::forward<Args>(args)...}); 
     } 
    }; 
} 

template<typename Ty, typename ...Args> 
std::unique_ptr<Ty> makeUnique(Args &&...args) { 
    return Aux::MakeUnique<Ty>::make(std::forward<Args>(args)...); 
}