系统相关
首页 > 系统相关> > c – 自定义运算符new []请求大于预期的内存

c – 自定义运算符new []请求大于预期的内存

作者:互联网

我无法解释为什么在示例代码中调用new Foo [4]到自定义运算符new []请求68个字节 – 比它应该多4个字节(sizeof(Foo)== 16)而更神秘的调用Foo :: operator new [](4 * sizeof(Foo))正确地请求64个字节.注意当成员std :: vector< long>从Foo中删除m_dummy两个调用都正确请求16个字节(ideone上的代码).

#include <vector>
#include <iostream>

struct MemoryManager
{
    static void* allocate( unsigned size )
    {
        static char block[256];
        return block;
    }
};

class Foo
{
public:
    void* operator new[]( size_t size )
    {
        std::cout << "operator new[] : data size -- " << size << std::endl;
        return MemoryManager::allocate( size );
    }  

private:
    std::vector<long> m_dummy;  // Huh?
    unsigned m_num;
};

int main( int argc, char * argv[] )
{
    std::cout << "Foo size: " << sizeof( Foo ) << std::endl;
    new Foo [4];
    Foo::operator new[]( 4 * sizeof( Foo ) );
}

解决方法:

根据标准(5.3.4新):

new T[5] results in a call of operator new[](sizeof(T)*5+x)

Here, x … are non-negative unspecified values representing array allocation overhead; the result of the
new-expression will be offset by this amount from the value returned by operator new[]. …

The amount of overhead may vary from one invocation of new to another.

实际上,它可以用来表示分配元素的数量.正如@vsoftco评论的那样,“这就是operator delete []知道如何执行清理的方式”.

请参见18.6.1.2数组表单中的脚注:

It is not the direct responsibility of operator new[](std::size_t) or operator delete[](void*) to note the repetition count or element size of the array. Those operations are performed elsewhere in the array new and delete expressions. The array new expression, may, however, increase the size argument to operator new[](std::size_t) to obtain space to store supplemental information.

标签:c,operator-overloading,new-operator
来源: https://codeday.me/bug/20190829/1762665.html