C++ DELETE 操作

 在C++中delete指针前不用进行指针是否为空的判断,因为delete的实现已经做了这件事情!
    使用delete来delete已释放的指针是一个严重的错误,所以要在delete完一个指针后手动把它置空!
因为delete空指针是安全的。

    以下是Bjarne Stroustrup's C++ Style and Technique FAQ中的 

Why doesn't delete zero out its operand?

Consider

	delete p;
// ...
delete p;
If the ... part doesn't touch p then the second "delete p;" is a serious error that a C++ implementation cannot effectively protect itself against (without unusual precautions). Since deleting a zero pointer is harmless by definition, a simple solution would be for "delete p;" to do a "p=0;" after it has done whatever else is required. However, C++ doesn't guarantee that.

One reason is that the operand of delete need not be an lvalue. Consider:

	delete p+1;
delete f(x);
Here, the implementation of delete does not have a pointer to which it can assign zero. These examples may be rare, but they do imply that it is not possible to guarantee that ``any pointer to a deleted object is 0.'' A simpler way of bypassing that ``rule'' is to have two pointers to an object:
	T* p = new T;
T* q = p;
delete p;
delete q; // ouch!
C++ explicitly allows an implementation of delete to zero out an lvalue operand, and I had hoped that implementations would do that, but that idea doesn't seem to have become popular with implementers.

If you consider zeroing out pointers important, consider using a destroy function:

	template<class T> inline void destroy(T*& p) { delete p; p = 0; }

Consider this yet-another reason to minimize explicit use of new and delete by relying on stadard library containers, handles, etc.

Note that passing the pointer as a reference (to allow the pointer to be zero'd out) has the added benefit of preventing destroy() from being called for an rvalue:

	int* f();
int* p;
// ...
destroy(f()); // error: trying to pass an rvalue by non-const reference
destroy(p+1); // error: trying to pass an rvalue by non-const reference

虽然以下的代码我在GCC可以编译通过,并且可以运行,但是结果会导致未定义行为!!!

#include <iostream>

int main(int argc, char *argv[])
{
    std::cout<<"Hello, world"<<'\n';
    
    int *= new int(10) ;

    std::cout<<i<<std::endl ;
    delete i ;
    std::cout<<i<<std::endl ;
    delete i ;
    return 0;
}

   上述代码的运行结果与编译器相关。(在VC2005中release也能运行,但是在debug模式就会抛异常)
   所以避免造成这种错误,在delete一个指针后对其置空!另外,只能delete由new分配的内存,而且要匹配格式。
    此外,根据exception c++上说的原则: 永远不要多态地处理数组.
    例如:

class D : public B
{
    /*******/
};

*pb = new D[10] ;
delete[] pb ;

//导致未定义行为

//所以优先使用vector和deque而不是数组

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值