C++98 auto_ptr智能指针

简介: C++98 auto_ptr智能指针

auto_ptr 是C++98定义的智能指针模板,其定义了管理指针的对象,可以将new获得(直接或间接)的地址赋给这种对象.当对象过期时,其析构函数将使用delete来释放内存!

用法:

头文件: #include<memory>

用法: auto_ptr <类型> 变量名(new 类型);

#include<iostream>
#include<memory>
using namespace std;
class test {
public:
  test() {
    cout << "调用构造函数" << endl;
  }
  ~test() {
    cout << "调用析构函数" << endl;
  }
};
int main(void) {
  // 语法:
  // auto_ptr<类型> 变量名(new 类型);
   //test* t = new test();//普通用法 不能自己析构
  auto_ptr<test>t(new test());
  return 0;
}

运行结果:

get : 获取指针

// get : 获取指针
cout << t.get() << endl;
test* temp = t.get();

release : 取消智能指针对动态内存的托管,此时内存必须由程序员手动释放

auto_ptr<test>t(new test());
// release : 取消智能指针对动态内存的托管,此时内存必须由程序员手动释放
test* temp = t.release();
delete temp;

reset : 重置智能指针托管的动态内存,如果地址不一致,原来的地址会被释放

(1)无参 :释放当前对象

//test* t = new test();//普通用法 不能自己析构
auto_ptr<test>t(new test());
// reset : 重置智能指针托管的动态内存,如果地址不一致,原来的地址会被释放
t.reset();

结果:

(2)有参:释放原来的对象,重新托管新的对象

auto_ptr<test>t(new test());
// reset : 重置智能指针托管的动态内存,如果地址不一致,原来的地址会被释放
//t.reset();
t.reset(new test());

结果:

使用建议:

(1).尽可能不要将auto_ptr变量定义为全局变量或指针

(2).除非自己知道后果,不要把auto_ptr 智能指针赋值给同类型的另外一个智能指针

(3).C++11 后auto_ptr已经被"抛弃",已使用unique_ptr代替!

auto_ptr 被C++11抛弃的主要原因:

//auto_ptr 被C++11抛弃的主要原因:
  auto_ptr<string>s1(new string("ABC"));
  auto_ptr<string>s2(new string("abc"));
  cout << "s1: " << s1.get() << endl;
  cout << "s2: " << s2.get() << endl;
  cout << "s1=s2" << endl;
  s1 = s2;
  cout << "s1: " << s1.get() << endl;
  cout << "s2: " << s2.get() << endl;

将智能指针s2赋值给s1,首先s1会释放,将s2赋值给s1,同时也会s2释放

结果:

auto_ptr陷阱,不能将同一段内存交给多个智能指针同时管理!!!(适用于所有智能指针)

//auto_ptr陷阱,不能将同一段内存交给多个智能指针同时管理
  string* s = new string("智能指针的内存管理陷阱");
  {
    auto_ptr<string>s2;
    s2.reset(s);
    {
      auto_ptr<string>s1;
      s1.reset(s);
      cout << "s: " << *s1 << endl;
    }
    cout << "s: " << *s2 << endl;
  }

结果:s1和s2同时管理s,当s被s1释放后,s2将无法访问s,编译不会报错,运行时崩溃.

不建议使用auto_ptr的原因以及auto_ptr的弊端:

因此:C++11 使用了更加严谨的unique_ptr替代了auto_ptr

目录
相关文章
|
5天前
|
C++ 数据格式
LabVIEW传递接收C/C++DLL指针
LabVIEW传递接收C/C++DLL指针
16 1
|
5天前
|
编译器 C++
C/C++杂谈——指针常量、常量指针
C/C++杂谈——指针常量、常量指针
9 0
|
5天前
|
C++ 编译器
|
5天前
|
存储 安全 程序员
C++:智能指针
C++:智能指针
22 5
|
5天前
|
存储 安全 C++
深入理解C++中的指针与引用
深入理解C++中的指针与引用
12 0
|
5天前
|
算法 C++
【C++入门到精通】智能指针 shared_ptr循环引用 | weak_ptr 简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 shared_ptr循环引用 | weak_ptr 简介及C++模拟实现 [ C++入门 ]
17 0
|
5天前
|
安全 算法 数据安全/隐私保护
【C++入门到精通】智能指针 shared_ptr 简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 shared_ptr 简介及C++模拟实现 [ C++入门 ]
14 0
|
5天前
|
存储 算法 安全
【C++入门到精通】智能指针 auto_ptr、unique_ptr简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 auto_ptr、unique_ptr简介及C++模拟实现 [ C++入门 ]
13 0
|
5天前
|
安全 算法 IDE
【C++入门到精通】智能指针 [ C++入门 ]
【C++入门到精通】智能指针 [ C++入门 ]
11 0
|
5天前
|
C语言
C语言:数组和指针笔试题解析(包括一些容易混淆的指针题目)
C语言:数组和指针笔试题解析(包括一些容易混淆的指针题目)