定义c-string的位置

Define where placed the c-string

本文关键字:位置 c-string 定义      更新时间:2023-10-16

我如何定义我需要调用"delete[]"指针或不在我的类的析构函数?指针(成员变量)可以在不同的时间指向在堆中分配或不分配的缓冲区(它可以是只读内存中的文字或堆栈中的文字)。最好的解决办法是什么?我是否需要为它使用另一个标志,或者可能是获取堆边界的地址并检查它们之间的缓冲区地址?还是有更理性的方式?

仅仅通过查看指针就无法判断指针是在自动存储库中、静态内存中还是动态内存中。在设置指针时需要存储一个标志,例如:

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