是以下新的重载泄漏内存? [英] is the following new overload leaking memory?
问题描述
我遇到了以下代码:
class a {
public:
void * operator new(size_t l, int nb);
double values;
};
void *a::operator new (size_t l,int n)
{
return new char[l+ (n>1 ? n - 1 : 0)*sizeof(double)];
}
根据我得到的结果, value:
From what I get it is then used to have an array like structure that start at "values":
double* Val = &(p->a->values) + fColumnNumber;
我的问题是:
是否有内存泄漏?我是非常新的重载new运算符,但我很确定分配的内存没有正确释放。这也意味着我不能在堆栈上创建一个a类?
My question is : is there a memory leak? I am very new to overloading new operator, but I'm pretty sure that the memory allocated is not deallocated properly. Also does that mean I can never create a "a" class on the stack?
感谢
推荐答案
我相信它在技术上生产UB,虽然它是一种形式的UB,可能永远不会产生可见的副作用(它使用 new []
,但是我相信会匹配 delete
- 但对于 char
t引起一个可见的问题)。
I believe it technically produces UB as it is, though it's a form of UB that will probably never cause a visible side effect (it's using new []
, but I believe that'll get matched up with delete
-- but for char
, this usually won't cause a visible problem).
IMO,几乎更糟糕的是,它使用一个新的表达式分配什么应该是真正的原始字节而不是对象。如果我这样做,我会这样写:
IMO, it's almost worse that it's using a new expression to allocate what should really be raw bytes instead of objects. If I were doing it, I'd write it like:
void *a::operator new (size_t l,int n)
{
return ::operator new(l+ (n>1 ? n - 1 : 0)*sizeof(double));
}
您可以将其与:
void a::operator delete(void *block)
{
::operator delete(block);
}
这篇关于是以下新的重载泄漏内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!