本文介绍了检查C ++中的指针定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检查C ++中是否定义了变量(尤其是指针)?假设我有一堂课:
How do I check if a variable, specifically a pointer, is defined in C++? Suppose I have a class:
class MyClass {
public:
MyClass();
~MyClass() {
delete pointer; // if defined!
}
initializePointer() {
pointer = new OtherClass();
}
private:
OtherClass* pointer;
};
推荐答案
为什么要担心检查指针值?只需将其初始化为空指针值,然后对其调用delete.空指针上的delete不会执行任何操作(标准保证了此操作).
Why worry about checking for the pointers value? Just initialize it to a null pointer value and then just call delete on it. delete on a null pointer does nothing (the standard guarantees it).
class MyClass {
public:
MyClass():pointer(0) { }
~MyClass() {
delete pointer;
pointer = 0;
}
initializePointer() {
pointer = new OtherClass();
}
private:
OtherClass* pointer;
};
每次调用delete时,都应将指针设置为空指针值.那你一切都好.
And everytime you call delete on it, you should set the pointer to a null pointer value. Then you are all fine.
这篇关于检查C ++中的指针定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!