实战c++中的智能指针unique_ptr系列-- 使用std::unique_ptr代替new operator(错误:‘unique_ptr’ is not a member of ‘std’)
2015-12-24 22:05
791 查看
写了很多篇关于vector的博客,其实vector很便捷,也很简单。但是很多易错的问题都是vector中的元素为智能指针所引起的。所以决定开始写一写关于智能指针的故事,尤其是unique_ptr指针的故事。
这是个开始,就让我们使用std::unique_ptr代替new operator吧!
还是用程序说话:
看下任务管理器中的内存:
此时使用智能指针unique_ptr:
两张图片就可以清晰看到智能指针带来的好处。
如果我们对传统的指针及时的释放,我们也可以达到智能指针的效果:
这里再分享一个错误,在MAC编辑器上写的C++代码,其中用到了智能指针unique_ptr,这个代码在vs2015中时候的时候,就会提示错误:
‘unique_ptr’ is not a member of ‘std’
原因很简单,就是缺少unique_ptr的头文件:
那么你也许会问题,智能指针是何时释放内存的呢?
unique_ptr objects automatically delete the object they manage (using a deleter) as soon as they themselves are destroyed, or as soon as their value changes either by an assignment operation or by an explicit call to unique_ptr::reset.
下一篇会从unique_ptr的构造函数说起!!
这是个开始,就让我们使用std::unique_ptr代替new operator吧!
还是用程序说话:
#include<iostream> int main() { while (true) int *x = new int; }
看下任务管理器中的内存:
此时使用智能指针unique_ptr:
#include<iostream> #include<memory> int main() { while (true) std::unique_ptr<int> x(new int(10)); }
两张图片就可以清晰看到智能指针带来的好处。
如果我们对传统的指针及时的释放,我们也可以达到智能指针的效果:
#include <iostream> using namespace std; int main() { while (true) { int *x = new int; delete x; } return 0; }
这里再分享一个错误,在MAC编辑器上写的C++代码,其中用到了智能指针unique_ptr,这个代码在vs2015中时候的时候,就会提示错误:
‘unique_ptr’ is not a member of ‘std’
原因很简单,就是缺少unique_ptr的头文件:
#include<memory>
那么你也许会问题,智能指针是何时释放内存的呢?
unique_ptr objects automatically delete the object they manage (using a deleter) as soon as they themselves are destroyed, or as soon as their value changes either by an assignment operation or by an explicit call to unique_ptr::reset.
下一篇会从unique_ptr的构造函数说起!!
相关文章推荐
- 实战c++中的智能指针unique_ptr系列-- 使用std::unique_ptr代替new operator(错误:‘unique_ptr’ is not a member of ‘std’)
- 极客必备之C++ 定时器
- C++为什么类的成员函数中(复制构造函数,赋值操作符等)可以有貌似类的对象访问类的私有成员的用法?
- 黑马程序员--C语言自学笔记---15C语言版通讯录
- 黑马程序员--C语言自学笔记---14static、extern、文件
- c语言学习(2)
- Leetcode 7 - Reverse Integer
- C++笔记——多态练习
- 黑马程序员--C语言自学笔记---13结构体、预编译、宏、条件编译
- POJ1035——Spell checker
- 实战c++中的vector系列--再谈vector的insert()方法(都是make_move_iterator惹的祸)
- 实战c++中的vector系列--再谈vector的insert()方法(都是make_move_iterator惹的祸)
- C++数组
- 为什么printf()用%f输出double型,而scanf却用%lf呢
- c++11新特性 lambda
- C++ Primer 学习笔记——类(二)
- C++笔记——类型兼容和多态
- c语言中几种常用变量类型
- 教你理解复杂的C-C++声明(下)
- 决策树C++实现