用于指针删除的 C++ 模式?

问题描述

我想知道是否有删除指针的模式。更具体地说,当您需要为数据调用某种中间函数时。这是我在想的一个例子:

int main() {
    // some code here

    char* return_of_function1 = function1(int_array);
    int return_of_function2 = function2(return_of_function1);
    delete[] return_of_function1;

    // some code here
} 

char* function1(int* int_array) {
    // some code here
}

int function2(char* char_array) {
    // some code here
}
int main() {
    // some code here

    int return_of_function2 = function2(int_array);

    // some code here
}

char* function1(int* int_array) {
    // some code here
}

int function2(int* int_array) {
    // some code here
    return function2(function1(int_array),true);
}

int function2(char* char_array,bool delete_array) {
    // some code here

    if(delete_array) {
        delete[] char_array;
    }

    return /* return value */;
}

动机是避免对集合属性数据的中间调用。同样,我只是在问这是否常用,或者甚至是一个好主意。

非常感谢。

解决方法

一般的做法是远离原始指针,就像您使用它们的方式一样。例如,如果您的 char * 确实是一个字符串,则使用 std::string。

RAII 代表资源获取即初始化。重要的是你用一个对象包装你的资源,你让这个对象超出范围。它会因超出范围而被破坏,而析构函数是您唯一需要担心破坏数据的地方。如果您真的要使用 char * 并且它不是真正的字符串,因此您应该使用字符串,它可能如下所示:

class CharArray {
public:
     CharArray(whatever args you need);
     virtual ~CharArray() { if (ptr) delete[] ptr; }
private:
     char * ptr = nullptr;
};

如果 CharArray 的任何方法实际上可以更改 ptr,那么您需要确保先小心地释放旧内容。

您还需要确保您拥有完整的移动构造函数/运算符等,以便您可以安全地返回它。

另一个选择是智能指针。请参阅 std::shared_ptrstd::unique_ptr。这些家伙很棒。他们通过引用计数为您处理所有这些。