How can I define do I need call "delete [ ]" for pointer or not in destructor of my class? Pointer (member-variable) can point out to buffer allocated in heap or not in different time (it can be a literal in read-only memory or a literal placed in stack). What the best way to resolve it? Do I need use just another flag for it or may be get addresses of heap boundry and check if buffer address between them? Or there is more rational way?
问问题
91 次
2 回答
2
- 不要使用动态分配的成员(使用
std::string
代替char *
或std::vector
代替动态分配的数据成员)或 - 使用智能指针
于 2013-04-30T15:09:11.400 回答
2
您无法仅通过查看指针来判断指针是在自动存储中、在静态内存中还是在动态内存中。您需要在设置该指针时存储一个标志 - 例如,如下所示:
class classWithDynamicData {
private:
bool needToDelete;
char strData[];
public:
classWithDynamicData(int size) : needToDelete(true), strData(new char[size]) {
}
classWithDynamicData(char* data) : needToDelete(false), strData(data) {
}
~classWithDynamicData() {
if (needToDelete) delete[] strData;
}
...
// You need to define a copy constructor and an assignment operator
// to avoid violating the rule of three
};
于 2013-04-30T15:09:21.137 回答