堆内存的管理

如大家所了解的,堆内存是向高地址扩展的数据结构,是不连续的内存区域。这是由于系统是用链表来存储的空闲内存地址的,自然是不连续的,而链表的遍历方向是由低地址向高地址。

对于堆资源的管理,可以说是 RAII 最典型的一种应用。当然我们可以自己简单实现一下,并观察其运行流程。

简单实现

#include <iostream>

class SmartPtr {
private:
    char* m_ptr;

public:
    SmartPtr(char* ptr = nullptr) {
        m_ptr = ptr;
        std::cout << "Execution the constructor" << std::endl;
    }
    ~SmartPtr() {
        delete[] m_ptr;
        std::cout << "Execution the destructor" << std::endl;
    }

    char* get() const {
        return m_ptr;
    }
};

SmartPtr division(int x, int y) {
    SmartPtr sp(new char[100]{});
    if (y == 0) {
        throw "Please do not use 0 as a divisor";
    }
    std::sprintf(sp.get(), "%d / %d = %d\n", x, y, x / y);
    return sp;
}

int main() {
    try {
        SmartPtr sp = division(6, 2);
        std::cout << sp.get() << std::endl;
    } catch (const char* e) {
        std::cerr << e << std::endl;
    }

    try {
        SmartPtr sp = division(6, 0);
        std::cout << sp.get() << std::endl;
    } catch (const char* e) {
        std::cerr << e << std::endl;
    }
}

* 提示:注意这里用到了一个叫做返回值优化的编译器优化。

Execution the constructor
6 / 2 = 3

Execution the destructor
Execution the constructor
Execution the destructor
Please do not use 0 as a divisor

更多推荐