前面介绍了C++98 的智能指针auto_ptr,现在来介绍一下它的替代品【unique_ptr】
看完,我也是醉了。好吧 我们继续
auto_ptr是用于C++11之前的智能指针。由于 auto_ptr 基于排他所有权模式:两个指针不能指向同一个资源,复制或赋值都会改变资源的所有权。auto_ptr 主要有三大问题:
- 复制和赋值会改变资源的所有权,不符合人的直觉。
- 在 STL 容器中使用auto_ptr存在重大风险,因为容器内的元素必需支持可复制(copy constructable)和可赋值(assignable)。
- 不支持对象数组的操作
先来看看auto_ptr的风险
#include <iostream>
#include <memory>
#include <vector>
#include <Windows.h>
#include <string>
#include <stdio.h>
using namespace std;
int
main(int argc, const char* argv[])
{
auto_ptr<string> str_ptr1(new string("Libero"));
auto_ptr<string> str_ptr2(new string("Martin"));
// 被C++11 抛弃的主要理由 p1= p2 ,复制或赋值都会改变资源的所有权
printf("str_ptr1: %p\n", str_ptr1.get());
printf("str_ptr2: %p\n", str_