🐭 RAII 黑魔法
系统的资源一般都是有限的,在 C++ 中资源管理一直是个让人头疼的问题。内存就是需要程序员手动管理的资源之一,内存的申请与释放必须严格匹配,否则,要么发生内存泄露,要么触发未定义行为。RAII「资源获取即初始化」是 C++ 中资源管理的超级英雄,它的设计思想是「用栈的思想来管理堆对象」,几乎在任何情况下都能管理好资源的释放问题。
代码示例 :
#include <iostream>// pseudo smart pointertemplate <typename T> class SmartPointer {public:explicit SmartPointer(T *p) : p_{p} {}~SmartPointer() {std::cout << "~SmartPointer\n";delete p_;}private:T *p_;};struct X {virtual ~X() { std::cout << "~X\n"; }};int main() {// 1. object allocated on the stack are// automatically destroyed when they go out of scope// x is a stack variable{ // beginning of a scopeX x;} // end of a scope, will call dtor, and print "~X"// 2. sp is a stack variable, but holds a heap object p_{ // beginning of a scopeSmartPointer<int> sp{new int(42)};} // end of a scope, will call dtor, and print "~SmartPointer" and delete p_return 0;}
:::tips 智能指针的设计思路是 RAII 的典型应用 :::
🐂 独占指针与原始指针
在 C++ 中指针是个强大的工具,非常灵活,但很难驾驭,主要是因为资源所有权问题,以及资源释放问题。独占指针的引入解决了独占所有权的资源管理问题,独占指针应该是最容易使用的一种智能指针,是我们需要在代码中第一优先级使用的智能指针。
代码示例 :
#include <iostream>struct X {virtual ~X() { std::cout << "~X\n"; }};void Xdeleter(X *x) {std::cout << "customer function pointer\n";delete x;}int main() {// 1. raw pointer{X *rp = new X();X *rpa = new X[2]();std::cout << sizeof(rp) << '\n'; // 8std::cout << sizeof(rpa) << '\n'; // 8delete rp;delete[] rpa;}// 2. unique_ptr{std::unique_ptr<X> up{new X()};std::unique_ptr<X[]> upa{new X[2]()};std::cout << sizeof(up) << '\n'; // 8std::cout << sizeof(upa) << '\n'; // 8}// 3. unique_ptr with customer lambda delete function{auto Xdeleter = [](X *x) {std::cout << "customer lambda\n";delete x;};std::unique_ptr<X, decltype(Xdeleter)> up(new X(), Xdeleter);std::cout << sizeof(up) << '\n'; // 8}// 4. unique_ptr with customer function pointer delete function{std::unique_ptr<X, std::function<void(X *)>> up(new X(), Xdeleter);std::cout << sizeof(up) << '\n'; // 64}// 5. never leak the pointer holds by a unique pointer{int *rp = new int(42);std::unique_ptr<int> up(rp);*rp = 24;std::cout << *up << '\n'; // 24}// 6. transfers ownership to another unique_ptr{auto up1 = std::make_unique<int>(42);auto up2 = std::move(up1);assert(up1 == nullptr);}// 7. reset a unique_ptr, replaces the managed object{auto up1 = std::make_unique<X>();std::cout << up1.get() << '\n'; // 0x7fe98cc05770up1.reset(new X());std::cout << up1.get() << '\n'; // 0x7fe98cc05780}return 0;}
:::tips
- 默认情况下,独占指针与原始指针大小相同,在使用了用户定制的删除函数之后,大小会有差异
- 用户定制的删除函数是独占指针类型的一部分,这个与后面介绍的共享指针不一样
- 另外,在 C++ 中使用原始数组的情况不多,可能主要是为了兼容 C 的一些情形
:::
🐯 独占指针与工厂设计模式
工厂设计模式是一种典型的设计模式,应用也比较广泛,独占指针非常适合工厂设计模式。注意我们可以从独占指针来构建共享指针,这个非常有用,能给调用方最大的自由度。
代码示例 : ```cppinclude
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
class FactoryA : public Factory {
public:
std::unique_ptr
class FactoryB : public Factory {
public:
std::unique_ptr
int main() {
std::unique_ptr
std::unique_ptr
🐰 总结
- 独占指针独占资源的所有权
- 用户定制的资源清理函数是独占指针类型的一部分,会影响其大小
- 可以方便的从独占指针来构建共享指针,这个使得独占指针能适应更多的上下文语境
