您的位置:首页 > 编程语言 > C语言/C++

实战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吧!

还是用程序说话:

#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的构造函数说起!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: