标签:c operator-overloading new-operator
我无法解释为什么在示例代码中调用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 ofoperator 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 operatornew[]
. …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)
oroperator delete[](void*)
to note the repetition count or element size of the array. Those operations are performed elsewhere in the arraynew
anddelete
expressions. The arraynew
expression, may, however, increase thesize
argument tooperator new[](std::size_t)
to obtain space to store supplemental information.
标签:c,operator-overloading,new-operator 来源: https://codeday.me/bug/20190829/1762665.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。