书店英语怎么读C++DELETE操作
在C++中delete指针前不⽤进⾏指针是否为空的判断,因为delete的实现已经做了这件事情!
使⽤delete来delete已释放的指针是⼀个严重的错误,所以要在delete完⼀个指针后⼿动把它置空!
七年级作文大全600字因为delete空指针是安全的。
以下是's C++ Style and Technique FAQ中的
Consider
delete p;
// ...
delete p;
If the ... part doesn't touch p then the cond "delete p;" is a rious error that a C++ implementation cannot effectively protect itlf 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 whatev
er el 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. The 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 em 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 u 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';
std::cout<<"Hello, world"<<'\n';
int*i =new int(10);
std::cout<<i<<std::endl;
delete i ;
std::cout<<i<<std::endl;
delete i ;
return 0;
}
上述代码的运⾏结果与编译器相关。(在VC2005中relea也能运⾏,但是在debug模式就会抛异常)
所以避免造成这种错误,在delete⼀个指针后对其置空!另外,只能delete由new分配的内存,⽽且要匹配格式。此外,根据exception c++上说的原则:永远不要多态地处理数组.
例如:
class D :public B
{
/*******/
};
B *pb =new D[10];
delete[] pb ;
拜金是什么意思//导致未定义⾏为
//所以优先使⽤vector和deque⽽不是数组