auto_ptr的一个简单例子
2006-03-17 09:50
387 查看
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,而这不是我们想看到的。
用法一
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,而这不是我们想看到的。
相关文章推荐
- auto_ptr的一个例子
- 一个简单的类似auto_ptr的类
- 智能指针auto_ptr简单使用例子
- 一个简单的C#多线程间同步的例子
- 用一个简单的例子来理解python高阶函数
- ant + junit 基础学习,一个简单易懂的例子
- 记录一个简单innerHTML例子
- 《HTML5游戏框架之CraftyJS》一个简单乒乓球游戏的例子
- SQL Server一个表添加数据,引发另一个表更新数据 的一个简单触发器例子
- 关于EJB3的一个简单例子
- proc编程的一个简单例子 http://blog.csdn.net/mailbox2005/article/details/3881538
- 一个简单的MyBatis完成插入操作的例子(二)
- 一个简单木马例子
- 一个简单jsp-servlet例子
- Spring 入门(一个简单的例子)
- 对Jena的简单理解和一个例子
- 一个简单的C#多线程间同步的例子【转】
- 关于ExpandableListView用法的一个简单小例子
- 【unity3d游戏开发之基础篇】unity3d射线的原理用法以及一个利用射线实现简单拾取的小例子
- 一个简单的struts2上传图片的例子