C++ | 动态内存

内容

  1. 动态内存和智能指针
  2. 动态数组
  3. 使用库:文本查询程序
  4. 总结

0. 摘要

动态分配的对象(dynamically allocated objects)的生命(lifetime)独立于其被创建的地方,他们一直会存在到被明确释放(free)。

为了让使用动态分配的对象更安全,库定义了两个智能指针(smart pointer)类型来管理动态分配的对象。智能指针能确保在合适的时候自动释放其指向的对象。

  • static memory and stack memory
    • static memory:
      • for local static objects
      • for class static data members
      • for variables defined outside any function
    • stack memory
      • for nonstatic objects defined inside functions
    • automatically created and destroyed by the compiler; static objects are allocated before they are used and are destroyed when the program ends.
  • heap memory (free store)
    • for dynamically allocated objects, that is, objects that the program allocate at run time.
    • must explicitly destroy

1. 动态内存和智能指针

operators:

  • new: 分配内存,初始化对象,返回一个指向那个对象的指针;
  • delete: 销毁对象,释放内存。

动态内存难点:

  • 内存泄露(memory leak):忘记释放内存
  • 非法指针:指向被释放的内存

智能指针(C++ 11):像普通指针一样使用,并且拥有一个重要特性,可以自动删除其指向的对象。

  • shared_ptr: allows multiple pointers to refer to the same object
    • weak_ptr: a weak reference to an object managed by a shared_ptr
  • unique_ptr: owns the object to which it points

1.1 shared_ptr class

像vector一样,智能指针也是模板。因此,在创建一个智能指针时,需要提供另外的信息,也就是其指向对象的类型。

shared_prt<string> p1; // shared_ptr可以指向一个字符串

使用智能指针的方式与使用一个指针类似。去引用(dereference)一个智能指针会返回其指向的对象。

// 如果p1不是空指针,检查其指向的空字符串 if (p1 && p1->empty()) *p1 = "hi"; // 去引用并赋新值给字符串

make_shared函数

分配和使用动态内存最安全的方式是调用一个库函数,“make_shared”。

#include <memory> // for the use of 'make_shared'

// shared_ptr that points to an int with value 42
shared_ptr<int> p3 = make_shared<int>(42);
// p4 points to a string with value 999999999
shared_ptr<string> p4 = make_shared<string>(10, '9');
// p5 points to an int that is value initialized to 0
shared_ptr<int> p5 = make_shared<int>();

2. 动态数组

3. 使用库:文本查询程序

4. 总结

参考

  • 《C++ Primer, Fifth Edition》, Stanley B. Lippman

猜你喜欢

转载自www.cnblogs.com/casperwin/p/12563628.html