Boost 智能指针

scoped_ptr
auto_ptr
unique_ptr
scoped_array
shared_ptr

------------------------------

#include<boost/timer.hpp>
#include<boost/progress.hpp>
#include<boost/date_time/gregorian/gregorian.hpp>
#include<boost/smart_ptr.hpp>
using namespace boost;
using namespace boost::gregorian;
#include<iostream>
#include<vector>
using namespace std;

struct posix_file {
 posix_file(const char * file_name) {
  cout << "open file:" << file_name << endl;
 }
 ~posix_file() {
  cout << "close file" <<endl;
 }
};

int main() {
 scoped_ptr<string> sp(new string("text"));

 cout << *sp << endl;
 cout << sp->size() << endl;

 scoped_ptr<int> p(new int);
 if(p) {
  *p = 100;
  cout << *p << endl;
 }

 p.reset();

 assert(p == 0);

 if(!p) {
  cout << "scope_ptr == null" << endl;
 }

 scoped_ptr<posix_file> fp(new posix_file("/temp/a.txt"));

 int *arr = new int[100];
 scoped_array<int> sa(arr);

 fill_n(&sa[0],100,5);
 sa[10]=sa[20] + sa[30];
 cout << sa[10] << endl;

 boost::shared_ptr<int> spi(new int);
 assert(spi);
 *spi = 253;

 cout << *spi << endl;
}
--------------------------------------------------------
shared_ptr 例程
--
 boost::shared_ptr<int> sp(new int(10));
 assert(sp.unique());
 
 boost::shared_ptr<int> sp2 = sp;

 assert(sp == sp2 && sp.use_count() == 2);

 *sp2 = 100;

 assert(*sp == 100);
 sp.reset();

 assert(!sp);


--------------------------------

make_shared

#include<boost/timer.hpp>
#include<boost/progress.hpp>
#include<boost/date_time/gregorian/gregorian.hpp>
#include<boost/smart_ptr.hpp>
using namespace boost;
using namespace boost::gregorian;
#include<iostream>
#include<vector>
using namespace std;

class shared {
private:
	boost::shared_ptr<int> p;
public:
	shared(boost::shared_ptr<int> _p):p(_p){}
	void print() {
		cout << "count:" << p.use_count()<< ",v = " << *p << endl;
	}
};

void print_func(boost::shared_ptr<int> p) {
	cout << "count:" << p.use_count() << ",v = " << *p <<endl;
}


int main() {
	boost::shared_ptr<int> p(new int(100));
	shared s1(p),s2(p);
	s1.print();
	s2.print();
	*p = 20;
	print_func(p);

	s1.print();

	boost::shared_ptr<string> sptr = boost::make_shared<string>("make_shared");
	boost::shared_ptr<vector<int>> spv = boost::make_shared<vector<int>>(10,2);
	cout << *sptr << endl;
}



你可能感兴趣的:(Boost 智能指针)