三個地方在 c++0x 而不是 c++11 時必須修改 :
1. using LargeArray= array<int,10000>; 改成 typedef array<int,10000> LargeArray ;
2. c++0x 沒有 lambda , [](){} 那邊就要割捨了.....
3. unique_ptr<array<int,10000>> 在 c++0x 必須改成 unique_ptr<array<int,10000> >
必須多一個 space 在 '10000>' 後面 !!
//http://scrupulousabstractions.tumblr.com/post/37576903218/cpp11style-no-new-delete
#include <thread>
#include <atomic>
#include <stdio.h>
#include <iostream>
#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>;
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 ;
}
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 ;
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.
}
留言列表