//http://scrupulousabstractions.tumblr.com/post/37576903218/cpp11style-no-new-delete
#include <thread>
#include <stdio.h>
#include <iostream>
#include <array>
#include "stlav_make_unique.hpp"
using namespace std;
struct my_point
{
int *x ;
int *y ;
};
struct my_point_deleter {
void operator()(my_point* p) const
{
cout << "my_point_deleter called" << endl ;
delete[] p->x;
delete[] p->y;
delete p ;
}
};
//using LargeArray= array<int,10000>;
typedef array<int,10000> LargeArray ;
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;
}
void DoPrint(my_point* p)
{
cout << p->x[0] << " " << p->y[1] << endl ;
}
void funcclose(FILE* f)
{
printf("file going to close \n") ;
fclose(f) ;
}
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 ;
}
unique_ptr<my_point,my_point_deleter> p1(new my_point) ;
p1->x = new int[10] ;
p1->y = new int[10] ;
p1->x[0] = 1000 ;
p1->y[1] = 2000 ;
cout << p1->x[0] << " " << p1->y[1] << endl ;
shared_ptr<my_point> p2(new my_point,my_point_deleter()) ;
p2->x = new int[100] ;
p2->y = new int[100] ;
p2->x[0] = 5000 ;
p2->y[1] = 6000 ;
cout << p2->x[0] << " " << p2->y[1] << endl ;
DoPrint(p2.get()) ;
cout << p2->x[0] << " " << p2->y[1] << endl ;
unique_ptr<FILE, void (*)(FILE*)> f(fopen("test.txt", "r"),funcclose) ;
/*There is no lambda in c++0x , In c++11 or boost exist, so ...
unique_ptr<FILE, void (*)(FILE*)> f(fopen("hanoi.c", "r"),[](FILE* f){cout << "going closed" << endl; fclose(f);});
char aux[100];
while (!feof(f.get())) //f.get returns me the actual plain old pointer
{
fgets(aux, 100, f.get());
cout << aux;
}//No need to invoke fclose() because the unique_ptr will take care of it.
*/
}
g++ --std=c++0x testunique_ptr.cpp -o testunique_ptr.exe
./testunique_ptr.exe
idx=3 5
idx=1 1
idx=100 100
1000 2000
5000 6000
5000 6000
5000 6000
file going to close
my_point_deleter called
my_point_deleter called
留言列表