跟auto_ptr对照一下,auto_ptr复制或转移拥有权,看看计数指针有什么不同,看看计数指针是怎么实现的?
#include<iostream>
#include<string>
#include<deque>
#include<algorithm>
#include<vector>
#include<list>
using namespace std;
template<typename T>
class CountedPtr{
private:
T* ptr;
long *count;
public:
explicit CountedPtr(T* p=0):ptr(p),count(new long(1)){}
CountedPtr(const CountedPtr<T>& p)throw():ptr(p.ptr),count(p.count){
++*count;
}
~CountedPtr()throw(){
dispose();
}
CountedPtr<T>& operator=(const CountedPtr<T>& p)throw(){
if(this!=&p){
dispose();
ptr=p.ptr;
count=p.count;
++*count;
}
return *this;
}
T& operator*()const throw(){
return *ptr;
}
T* operator->()const throw(){
return ptr;
}
private:
void dispose(){
if(--*count==0){
delete count;
delete ptr;
}
}
};
void dayin(CountedPtr<int> elem){
cout<<*elem<<" ";
}
int main(){
static int values[]={3,5,9,1,6,4};
typedef CountedPtr<int> InPtr;
deque<InPtr>d;
list<InPtr>l;
for(int i=0;i<sizeof(values)/sizeof(*values);++i){
InPtr ptr(new int(values[i]));
d.push_back(ptr);
l.push_front(ptr);
}
for_each(d.begin(),d.end(),dayin);
cout<<endl;
for_each(l.begin(),l.end(),dayin);
cout<<endl;
*d[2]*=*d[2];
(**d.begin())*=-1;
(**d.begin())=0;
for_each(d.begin(),d.end(),dayin);
cout<<endl;
for_each(l.begin(),l.end(),dayin);
cout<<endl;
system("pause");
return 0;
}