1.auto_ptr 被複制後,将失去原來所緻資源的所有權;
2.scoped_ptr永遠不能被複制或被指派!scoped_ptr 擁有它所指向的資源的所有權,并永遠不會放棄這個所有權;
3.shared_ptr 是可以共享所有權的智能指針;
#include "stdafx.h"
//#include "windows.h"
#include <memory>
#include <iostream>
using std::tr1::shared_ptr;
class Foo
{
public:
Foo()
{
std::cout<<"new Foo()"<<std::endl;
i = 0;
}
~Foo()
{
std::cout<<"destroy Foo()"<<std::endl;
}
void print()
{
std::cout<<"Foo::print"<<std::endl;
}
int i;
};
void OutSharePtr(shared_ptr<Foo> &P)
{
Foo* p = new Foo();
shared_ptr<Foo> sp1(p);
std::cout<<sp1.use_count()<<"::"<<sp1.get()<<std::endl;
shared_ptr<Foo> sp2(sp1);
p->print();
sp2->print();
std::cout<<sp1.use_count()<<"::"<<sp1.get()<<std::endl;
P = sp2;
std::cout<<sp1.use_count()<<"::"<<sp1.get()<<std::endl;
}
void InSharePtr(shared_ptr<Foo> &p)
{
p->i += 100;
std::cout<<p.use_count()<<"::"<<p.get()<<std::endl;
}
#include <algorithm>
char upCase(char c)
{
return toupper(c);
}
int _tmain(int argc, _TCHAR* argv[])
{
shared_ptr<Foo> sp1(new Foo());
shared_ptr<Foo> sp2(sp1);
shared_ptr<Foo> sp3;
sp1->print();
sp2->print();
std::cout<<sp1.use_count()<<"::"<<sp1.get()<<std::endl;
std::cout<<sp3.use_count()<<"::"<<sp3.get()<<std::endl;
sp3.swap(sp1);
std::cout<<sp1.use_count()<<"::"<<sp1.get()<<std::endl;
std::cout<<sp3.use_count()<<"::"<<sp3.get()<<std::endl;
sp3.reset();
std::cout<<sp1.use_count()<<"::"<<sp1.get()<<std::endl;
sp2.reset();
std::cout<<sp1.use_count()<<"::"<<sp1.get()<<std::endl;
sp1.reset();
std::cout<<sp1.use_count()<<"::"<<sp1.get()<<std::endl;
return 0;
}