1

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?

4

2 回答 2

2
  1. 不要使用动态分配的成员(使用std::string代替char *std::vector代替动态分配的数据成员)或
  2. 使用智能指针
于 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 回答