以前为了让指针自动释放,曾经这么做过
#include <iostream>
template<class T>
class AutoPtr
{
public:
AutoPtr(T& t){m_t = t;};
virtual ~AutoPtr()
{
if(m_t)
{
delete[] m_t;
std::cout<<"destroy"<<std::endl;
}
};
private:
T m_t;
};
class A
{
};
int main(int argc, char* argv[])
{
char * pchar = new char[100];
{
AutoPtr<char*> autoptr(pchar);
}
int * pint = new int[100];
{
AutoPtr<int*> autoptr(pint);
}
A * pA = new A;
{
AutoPtr<A *> autoptr(pA);
}
system("pause");
return 0;
}
虽然能够达到自动释放的目的,然而却是个半成品。
boost::scoped_ptr 的出现解决这个问题
#include <iostream>
#include <boost/scoped_ptr.hpp>
class A
{
public:
~A() { std::cout <<"destroying A\n"; }
void do_something() { std::cout << "did something\n"; }
};
void test()
{
boost::scoped_ptr<A> impl(new A());
impl->do_something();
}
void main()
{
test();
}