🐭 RAII 黑魔法

系统的资源一般都是有限的,在 C++ 中资源管理一直是个让人头疼的问题。内存就是需要程序员手动管理的资源之一,内存的申请与释放必须严格匹配,否则,要么发生内存泄露,要么触发未定义行为。RAII「资源获取即初始化」是 C++ 中资源管理的超级英雄,它的设计思想是「用栈的思想来管理堆对象」,几乎在任何情况下都能管理好资源的释放问题。
代码示例 :

  1. #include <iostream>
  2. // pseudo smart pointer
  3. template <typename T> class SmartPointer {
  4. public:
  5. explicit SmartPointer(T *p) : p_{p} {}
  6. ~SmartPointer() {
  7. std::cout << "~SmartPointer\n";
  8. delete p_;
  9. }
  10. private:
  11. T *p_;
  12. };
  13. struct X {
  14. virtual ~X() { std::cout << "~X\n"; }
  15. };
  16. int main() {
  17. // 1. object allocated on the stack are
  18. // automatically destroyed when they go out of scope
  19. // x is a stack variable
  20. { // beginning of a scope
  21. X x;
  22. } // end of a scope, will call dtor, and print "~X"
  23. // 2. sp is a stack variable, but holds a heap object p_
  24. { // beginning of a scope
  25. SmartPointer<int> sp{new int(42)};
  26. } // end of a scope, will call dtor, and print "~SmartPointer" and delete p_
  27. return 0;
  28. }

:::tips 智能指针的设计思路是 RAII 的典型应用 :::

🐂 独占指针与原始指针

在 C++ 中指针是个强大的工具,非常灵活,但很难驾驭,主要是因为资源所有权问题,以及资源释放问题。独占指针的引入解决了独占所有权的资源管理问题,独占指针应该是最容易使用的一种智能指针,是我们需要在代码中第一优先级使用的智能指针。
代码示例 :

  1. #include <iostream>
  2. struct X {
  3. virtual ~X() { std::cout << "~X\n"; }
  4. };
  5. void Xdeleter(X *x) {
  6. std::cout << "customer function pointer\n";
  7. delete x;
  8. }
  9. int main() {
  10. // 1. raw pointer
  11. {
  12. X *rp = new X();
  13. X *rpa = new X[2]();
  14. std::cout << sizeof(rp) << '\n'; // 8
  15. std::cout << sizeof(rpa) << '\n'; // 8
  16. delete rp;
  17. delete[] rpa;
  18. }
  19. // 2. unique_ptr
  20. {
  21. std::unique_ptr<X> up{new X()};
  22. std::unique_ptr<X[]> upa{new X[2]()};
  23. std::cout << sizeof(up) << '\n'; // 8
  24. std::cout << sizeof(upa) << '\n'; // 8
  25. }
  26. // 3. unique_ptr with customer lambda delete function
  27. {
  28. auto Xdeleter = [](X *x) {
  29. std::cout << "customer lambda\n";
  30. delete x;
  31. };
  32. std::unique_ptr<X, decltype(Xdeleter)> up(new X(), Xdeleter);
  33. std::cout << sizeof(up) << '\n'; // 8
  34. }
  35. // 4. unique_ptr with customer function pointer delete function
  36. {
  37. std::unique_ptr<X, std::function<void(X *)>> up(new X(), Xdeleter);
  38. std::cout << sizeof(up) << '\n'; // 64
  39. }
  40. // 5. never leak the pointer holds by a unique pointer
  41. {
  42. int *rp = new int(42);
  43. std::unique_ptr<int> up(rp);
  44. *rp = 24;
  45. std::cout << *up << '\n'; // 24
  46. }
  47. // 6. transfers ownership to another unique_ptr
  48. {
  49. auto up1 = std::make_unique<int>(42);
  50. auto up2 = std::move(up1);
  51. assert(up1 == nullptr);
  52. }
  53. // 7. reset a unique_ptr, replaces the managed object
  54. {
  55. auto up1 = std::make_unique<X>();
  56. std::cout << up1.get() << '\n'; // 0x7fe98cc05770
  57. up1.reset(new X());
  58. std::cout << up1.get() << '\n'; // 0x7fe98cc05780
  59. }
  60. return 0;
  61. }

:::tips

  1. 默认情况下,独占指针与原始指针大小相同,在使用了用户定制的删除函数之后,大小会有差异
  2. 用户定制的删除函数是独占指针类型的一部分,这个与后面介绍的共享指针不一样
  3. 另外,在 C++ 中使用原始数组的情况不多,可能主要是为了兼容 C 的一些情形 :::

    🐯 独占指针与工厂设计模式

    工厂设计模式是一种典型的设计模式,应用也比较广泛,独占指针非常适合工厂设计模式。注意我们可以从独占指针来构建共享指针,这个非常有用,能给调用方最大的自由度。
    代码示例 : ```cpp

    include

    include

class Product { public: virtual ~Product() = default; virtual void do_stuff() const = 0; };

class ProductA final : public Product { public: void do_stuff() const override { std::cout << “ProductA\n”; } };

class ProductB final : public Product { public: void do_stuff() const override { std::cout << “ProductB\n”; } };

class Factory { public: virtual ~Factory() = default; virtual std::unique_ptr make_product() const = 0; };

class FactoryA : public Factory { public: std::unique_ptr make_product() const override { return std::make_unique(); } };

class FactoryB : public Factory { public: std::unique_ptr make_product() const override { return std::make_unique(); } };

int main() { std::unique_ptr ufa(new FactoryA()); auto pa = ufa->make_product(); pa->do_stuff(); // ProductA

std::unique_ptr ufb(new FactoryB()); std::shared_ptr pb = ufb->make_product(); // pb is a shared pointer pb->do_stuff(); // ProductB

return 0; } ```

🐰 总结

  1. 独占指针独占资源的所有权
  2. 用户定制的资源清理函数是独占指针类型的一部分,会影响其大小
  3. 可以方便的从独占指针来构建共享指针,这个使得独占指针能适应更多的上下文语境