坛友们,这段代码会内存泄露?
如下代码,delete pa;以后,内存泄露吗?欢迎讨论^_^
class A
{
public:
A(){}
virtual void f(){}
private:
int m_a;
};
class B : public A
{
public:
virtual void f(){}
private:
int m_b;
};
int main()
{
A *pa = new B;
delete pa;
pa = NULL;
return 0;
}
[解决办法]
class C:public B
{
char * p;
public:
C(){p=new char[128];}
~C(){delete [] p;}
};
delete = 调用析构函数(至于调用的是谁那是语法的事) + free(分配的sizeof(B)空间)
不要被C++的什么继承迷惑了,在底层只有指针和数据。
[解决办法]
不会泄露, 看了楼主的故事! 感觉那个面试官吧, 很二
但是楼主没必要发那么大火
这个东西么 平时大家加上个virtual就可以了 免得跟他废话
[解决办法]
这个问题越来越有趣了。
A所说“有的编译器会,有的不会”又引起了我更多的思考,其实问题就在于这个未定义行为是否包括解除分配函数没有被调用或者失败、失效,标准的相关内容:
5.3.5 Delete
1 The delete-expression operator destroys a most derived object (1.8) or array created by a new-expression.
delete-expression:
::opt delete cast-expression
::opt delete [ ] cast-expression
.....
3 In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.73)
但是,标准也规定了一条确定的条款:
......
7 The delete-expression will call a deallocation function (3.7.3.2).
就是说,无论是否发生未定义行为,解除分配函数是一定会调用的,而只要满足传入的指针值(delete只关心指针值)是相应new返回的指针值,调用解除分配函数是一定会导致new所分配的n个字节的内存被释放的,除非指针值是非法的。
标准的内容:
3.7.3.2 Deallocation functions
.........
3 The value of the first argument supplied to one of the deallocation functions provided in the standard library may be a null pointer value; if so, the call to the deallocation function has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(size_t) or operator new(size_t, const std::nothrow_t&) in the standard library, and the value supplied to operator
delete[](void*) in the standard library shall be one of the values returned by a previous invocation of either operator new[](size_t) or operator new[](size_t, const std::nothrow_t&)in the standard library.
4 If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value (4.10), the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. The effect of using an invalid
pointer value (including passing it to a deallocation function) is undefined.33)
因此我仍然倾向于不会发生内存泄漏,但尚未100%确定,因为上述依据是否足够尚存一点点疑虑。
[解决办法]
不会有泄漏,因为析构函数是trival的