//http://scrupulousabstractions.tumblr.com/post/37576903218/cpp11style-no-new-delete
/* stephantl_make_unique.h
 * Based on code by Stephan T. Lavavej at http://channel9.msdn.com/Series/
 * C9-Lectures-Stephan-T-Lavavej-Core-C-/STLCCSeries6
 */

#ifndef STEPHANTL_MAKE_UNIQUE_H_
#define STEPHANTL_MAKE_UNIQUE_H_

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

namespace fut_stl {
    namespace impl_fut_stl {
    template<typename T, typename ... Args>
            std::unique_ptr<T> make_unique_helper(std::false_type, Args&&... args) {
            return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
        }

        template<typename T, typename ... Args>
        std::unique_ptr<T> make_unique_helper(std::true_type, Args&&... args) {
            static_assert(std::extent<T>::value == 0,
                    "make_unique<T[N]>() is forbidden, please use make_unique<T[]>(),");
            typedef typename std::remove_extent<T>::type U;
            return std::unique_ptr<T>(new U[sizeof...(Args)]{std::forward<Args>(args)...});
        }
    }

    template<typename T, typename ... Args>
    std::unique_ptr<T> make_unique(Args&&... args) {
        return impl_fut_stl::make_unique_helper<T>(
            std::is_array<T>(),std::forward<Args>(args)... );
    }
}
#endif

 

#include <thread>
#include <atomic>
#include <stdio.h>
#include <iostream>
#include "stlav_make_unique.hpp"
  
  
using namespace std;
  
using LargeArray= array<int,10000>; 
  
unique_ptr<LargeArray> giveMeMyArray(){
    unique_ptr<LargeArray> myObj(new LargeArray() );
    myObj->at(3)=5;
    return myObj;
}
  
unique_ptr<LargeArray> giveMeMyArray2(){
    unique_ptr<LargeArray> myObj = fut_stl::make_unique<LargeArray>();
    myObj->at(1)=1;
    myObj->at(100)=100;
    return myObj;
}
  
  
int main()
{
    unique_ptr<LargeArray> ptr ;
    ptr = giveMeMyArray() ;
    for(int idx=0;idx<10000;idx++)
    {
        if(ptr->at(idx) >0)
            cout << "idx=" << idx << " " << ptr->at(idx) << endl ;
    }
    unique_ptr<LargeArray> ptr2 ;
    ptr2 = giveMeMyArray2() ;
    for(int idx=0;idx<10000;idx++)
    {
        if(ptr2->at(idx) >0)
            cout << "idx=" << idx << " " << ptr2->at(idx) << endl ;
    }
      
}
 
創作者介紹
創作者 hedgezzz 的頭像
hedgezzz

hedgezzz的部落格

hedgezzz 發表在 痞客邦 留言(0) 人氣()