:: operator delete(pointer)返回释放的字节大小?

时间:2017-01-25 21:49:06

标签: c++

当你使用:: operator delete(pointer)?

时,有一些方法可以获得释放的字节大小

我尝试在doc中搜索并且有一个size_t参数,但我认为这是给你想要释放的字节,而不是返回释放的字节大小。

谢谢!

1 个答案:

答案 0 :(得分:0)

可能有点晚了,但是我今天才学到这一点。如果启用了C ++ 14支持,则会使void operator delete(void*, std::size_t)

重载

参考: https://en.cppreference.com/w/cpp/memory/new/operator_delete-这列出了operator delete

的所有可能的签名

https://en.cppreference.com/w/cpp/language/delete-这列出了如何选择删除运算符

下面是我用来弄清楚其工作方式的代码。它在Visual Studio 2017中编译,语言支持设置为C ++ 14或更高版本。 HTH。


#include <iostream>
#include <memory>

auto test_counter_reserved_memory{ 0u };

void* operator new(std::size_t sz) {
    test_counter_reserved_memory += static_cast<unsigned int>(sz);
    return std::malloc(sz);
}

void operator delete(void* ptr) noexcept
{
    std::cout << "Called: void operator delete(void* ptr)" << std::endl;
    std::free(ptr);
}

void operator delete(void* ptr, std::size_t sz) 
{
    std::cout << "Called: void operator delete(void* ptr, std::size_t sz)" << std::endl;
    test_counter_reserved_memory -= static_cast<unsigned int>(sz);
    std::free(ptr);
}

int main()
{
    test_counter_reserved_memory = 0u;

    {
        std::cout << "before: " << test_counter_reserved_memory << std::endl;
        auto p = std::make_unique<int>(750000);
        std::cout << "allocated: " << test_counter_reserved_memory << std::endl;
    }
    std::cout << "after: " << test_counter_reserved_memory << std::endl;


    // set breakpoint here to see results.
    return 0;
}