重载内存跟踪器的delete[]运算符

问题描述 投票:0回答:1

为了跟踪内存分配,我一直在尝试重载 C++ 中

new
delete
运算符的标量和数组版本。但是,
delete[]
的重载不起作用。我一直在尝试理解 cppreference 的文档(https://en.cppreference.com/w/cpp/memory/new/operator_delete),但无法理解它。我想我对重载 # 5 感兴趣,它如下,但可能是错误的。

void operator delete  ( void* ptr, std::size_t sz ) noexcept;

这是我目前正在测试我的想法的程序以及我编写的所有函数。 请注意,我对可与内置类型和我创建的任何类/结构一起使用的内存分配器感兴趣。

#include<iostream>

// global variable
std::size_t g_allocatedMemory{};

// =======================================================================
// global overload for new
void* operator new(std::size_t size)
{
    g_allocatedMemory += size;
    
    std::cout << "Allocating " << size << " bytes\n";
    std::cout << "Current allocation = " << g_allocatedMemory << " bytes\n\n";

    return malloc(size);
}

// global overload for delete
void operator delete(void* memory, std::size_t size)
{
    g_allocatedMemory -= size;

    std::cout << "Freeing " << size << " bytes\n";
    std::cout << "Current allocation = " << g_allocatedMemory << " bytes\n\n";
    
    free(memory);
}

// =======================================================================

// global overload for new[]
void* operator new[](std::size_t size)
{
    g_allocatedMemory += size;
    
    std::cout << "Allocating " << size << " bytes\n";
    std::cout << "Current allocation = " << g_allocatedMemory << " bytes\n\n";

    return malloc(size);
}

// global overload for delete[]
void operator delete[](void* memory, std::size_t size)
{    
    g_allocatedMemory -= size;

    std::cout << "Freeing " ;//<< size << " bytes\n";
    std::cout << "Current allocation = " << g_allocatedMemory << " bytes\n\n";
    
    free(memory);
}

// =======================================================================

int main()
{
    int* p{ new int[5] };

    delete[] p;

    return 0;
}

我也尝试过 C++17;这不起作用。

该程序不使用我为

delete[]
提供的重载。因此,当我在
delete[] p
main()
时,只有
int* p{ new int[5] };
的输出打印在屏幕上,而
delete[] p;
没有任何输出:

Allocating 20 bytes
Current allocation = 20 bytes

这就是我编译代码的方式。

g++ -pedantic-errors -Wall -Weffc++ -Wextra -Wconversion -Wsign-conversion -std=c++14 .\leak.cpp

c++ oop memory memory-management
1个回答
0
投票

您必须提供一个运算符delete[](void *ptr) noexcept函数。

注意,标准在替换带尺寸的版本时需要替换非尺寸版本。

只需添加以下代码即可使用重载。

// global overload for delete[]
void operator delete[](void* memory)
{     
    std::cout << "test" << std::endl;
}

带有此额外重载的代码将输出:

Allocating 20 bytes
Current allocation = 20 bytes

test

我希望这对您的努力有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.