c++中申请指针通常采用的方式是new和delete。然而标准c++中还有一个强大的模版类就是auto_ptr,它可以在你不用的时候自动帮你释放内存。下面简单说一下用法。
用法一
std::auto_ptr<MyClass>m_example(new MyClass());
用法二
std::auto_ptr<MyClass>m_example;
m_example.reset(new MyClass());
用法三(指针的赋值操作)
std::auto_ptr<MyClass>m_example1(new MyClass());
std::auto_ptr<MyClass>m_example2(new MyClass());
m_example2=m_example1;
则c++会把m_example所指向的内存回收,使m_example 的值为null,所以在c++中,应绝对避免把auto_ptr放到容器中。即应避免下列代码
vector<auto_ptr<MyClass>>m_example;
当用算法对容器操作的时候,你很难避免stl内部对容器中的元素实现赋值传递,这样便会使容器中多个元素被置位null,而这不是我们想看到的。