//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 <stdio.h>
#include <string.h>
#include <thread>
#include <iostream>
#include <memory>
#include "stlav_make_unique.hpp"
using namespace std ;
class People
{
private:
int age ;
char name[64] ;
public :
People(char* name_,int age_=10)
{
age = age_ ;
strncpy(name,name_,63) ;
name[63]=0x00 ;
printf("People Constrcted \n") ;
}
~People()
{
printf("%s desctrued \n",name) ;
}
const int getAge() const { return age ;}
const char* getName() const { return name; }
} ;
void func(unique_ptr<People> p)
{
printf("(%s) in func \n",p->getName() ) ;
}
void func2(People* p)
{
printf("(%s) in func \n",p->getName() ) ;
}
int main()
{
char name1[] = "Mars Chen" ;
unique_ptr<People> p1(new People(name1)) ;
func(move(p1)) ;
printf("after func \n") ;
printf("========================== \n") ;
char name2[] = "Judy Leu" ;
shared_ptr<People> p2=std::make_shared<People>(name2,33);
func2(p2.get()) ;
printf("after func2 \n") ;
printf("========================== \n") ;
char name3[] = "Cheng Ming Wang" ;
unique_ptr<People> p3 = fut_stl::make_unique<People>(name3,44);
func(move(p3)) ;
printf("after func \n") ;
}
g++ --std=c++0x testxxx.cpp -o testxxx.exe
./testxxx.exe
People Constrcted
(Mars Chen) in func
Mars Chen desctrued
after func
==========================
People Constrcted
(Judy Leu) in func
after func2
==========================
People Constrcted
(Cheng Ming Wang) in func
Cheng Ming Wang desctrued
after func
Judy Leu desctrued
留言列表