c++11新特性:智能指针
#ifndef _smart_str
#define _smart_str
#include<iostream>
using namespace std;
class use {
public:
void method(){ cout << "Method is called!" << endl; }
};
template <typename T>
class smart_ptr {
private:
T* px;
int* pn;
public:
smart_ptr(T* p) ;
smart_ptr(const smart_ptr<T>& ori);
smart_ptr<T>& operator=(const smart_ptr<T>& rig);
~smart_ptr();
T& operator*()const;
T* operator->()const;
void getcount() {
return *pn;
}
};
template <typename T>
smart_ptr<T>::smart_ptr(T* p) :px(p)
{
try
{
pn = new int(1);
}
catch (const std::exception&)
{
delete px;
px = nullptr;
delete pn;
pn = nullptr;
}
cout << "Constructor is called!" << endl;
}
template <typename T>
smart_ptr<T>::smart_ptr(const smart_ptr<T>& ori) {
pn = ori.pn;
px = ori.px;
++(*ori.pn);
cout << "Copy Constructor is called!" << endl;
}
template <typename T>
smart_ptr<T>& smart_ptr<T>::operator=(const smart_ptr<T>& rig) {
if (this->px == rig.px)
{
cout << "Self assignment is called!" << endl;
return *this;
}
if (--(*pn) == 0) {
delete px;
px=nullptr;
delete pn;
pn=nullptr;
}
++(*rig.pn);
px = rig.px;
pn = rig.pn;
cout << "Assignment operator overloaded is called!" << endl;
return *this;
}
template <typename T>
T& smart_ptr<T>::operator*()const {
cout << "Assignment operator* overloaded is called!" << endl;
return *px;
}
template <typename T>
T* smart_ptr<T>::operator->()const {
cout << "Assignment operator-> overloaded is called!" << endl;
return px;
}
template <typename T>
smart_ptr<T>::~smart_ptr() {
if (--(*pn) == 0) {
delete pn;
delete px;
px = nullptr;
pn = nullptr;
cout << "Destructor is called!" << endl;
}
}
int main() {
smart_ptr<int> p1(new int(0));
p1 = p1;
cout << *p1;
smart_ptr<int> p2(p1);
smart_ptr<int> p3(new int(1));
smart_ptr<use> sp(new use);
sp->method();
p3 = p1;
return 0;
}
#endif