乐趣区

关于c++:C内存管理4内存分配的重载

C++ 应用程序,内存调配的路径

默认的内存调配形式

对于 ① 处的阐明 (成员函数的自定义内存调配)

 可通过自定义内存池的形式进步应用效率,如更快的调配速度,更省的内存空间(省去 cookie)

对于 ② 处的阐明 (重载全局空间的内存管理策略)

 全局的内存管理策略会被多处无意或无心的应用,代码会大范畴的收到影响,可重载但少见

容器的内存调配形式

  • 容器并未采纳默认的内存治理形式,而采纳内存分配器从新实现
  • 内存调配与结构被从新封装彼此拆散
  • 内存开释与析构被从新封装彼此拆散
Foo *p = (Foo)operator new(sizeog(Foo));  // 内存申请
new(p) Foo(x);                            // 结构
...
p->~Foo();                                // 析构
operator delete(p);                       // 内存开释 

全局重载 ::operator new / ::operator delete

void *myAlloc(size_t size)
{return malloc(size);
}

void myFree(void *ptr)
{return free(ptr);
}

void *operator new(size_t size)
{
    cout << "global new" << endl;

    return myAlloc(size);
}

void *operator new[] (size_t size)
{cout << "global new[]" << endl;

    return myAlloc(size);
}

void operator delete(void *ptr) noexcept
{
    cout << "global delete" << endl;

    myFree(ptr);
}

void operator delete[] (void *ptr) noexcept
{
    cout << "global delete" << endl;

    myFree(ptr);
}

operator new 的一种实现 […\vc98\src\newop.cpp]

void *operator new(size_t size, const std::nothrow_t &_THROW0())
{
    // try to allocate size bytes
    void *p;
    while ((p == malloc(size)) == 0)
    {
        // buy more memory or return null pointer
        __TRY_BEGIN
            if (_callnewh(size) == 0) break;
        __CATCH(std::bad_alloc) return (0);
        __CATCH_END;
    }
    
    return (p);
}

operator delete 的一种实现 […\vc98\src\delop.cpp]

void __cdecl operator delete(void *p) _THROW0()
{
    // free an allocated object
    free(p);
}

类内重载 operator new/operator delete

class Foo {
public:
    void *operator new(size_t);
    void operator delete(void*, size_t[ 可选]);
}

------------------------------

Foo *p = new Foo;
==>
try {void *mem = operator new(sizeof(Foo));
    p = static_cast<Foo*>(sizeof(Foo));
    p->Foo::Foo();}

------------------------------

delete p;
==>
p->~Foo();
operator delete(p);

类内重载 operator new, operator delete 的成员函数具备 static 属性

 非动态成员函数须要对象(暗藏的 this 指针)实现调用,而 operator new 被调用时示意对象正在被创立 

类内重载 operator new[]/operator delete[]

class Foo {
public:
    void *operator new[](size_t);
    void operator delete[](void*, size_t[ 可选]);
    // ...
};

------------------------------

Foo *p = new Foo[N];
==>
try {void *mem = operator new(sizeof(Foo) * N + 4);
    p = static_cast<Foo*>(mem);
    p->Foo::Foo();    // N 次}

------------------------------

delete[] p;
==>
p->~Foo();            // N 次
operator delete(p);

类内重载 operator new[], operator delete[] 的成员函数具备 static 属性

 非动态成员函数须要对象(暗藏的 this 指针)实现调用,而 operator new[] 被调用时示意对象正在被创立 
退出移动版