删除后指针未设置为nullptr

Ian*_*ing 1 c++ pointers

我在函数中delete的指针,然后我设置为.但是,在运行该函数后,不再设置,所以我必须再次设置它.aStudentdestroyStudent()aStudentnullptraStudentnullptrnullptr

#include <cstring>

using namespace std;

struct Student {
   char *     name;
   float      gpa;
};

Student * createStudent(const char name[], float gpa) {
    struct Student * student = new Student;
    student->name = (char*)malloc(strlen(name + 1)); //allocate only enough memory to fit the given name
    strcpy(student->name, name);
    student->gpa = gpa;

    return student;
}

bool destroyStudent(Student * aStudent) {
    if(aStudent) { //check whether this pointer is already null.
        free(aStudent->name);
        delete aStudent; // ******This is where the issue is******
        aStudent = nullptr;
        return true;
    }
    return false; //aStudent is already null
}


int main() {
    Student * student1 = createStudent("Charles", 2.5);
    cout << student1->name << " and " << student1->gpa << endl;
    destroyStudent(student1);
    if(student1) {
        cout << "Pointer is NOT null!!!" << endl;
        student1 = nullptr;
    }

    if(!student1) {
        cout << "The pointer is null now." << endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Gal*_*lik 6

问题是aStudent指针的本地副本.

您需要通过引用传递指针,如下所示:

bool destroyStudent(Student*& aStudent) {
    if(aStudent) { //check whether this pointer is already null.
        free(aStudent->name);
        delete aStudent; // ******This is where the issue is******
        aStudent = nullptr;
        return true;
    }
    return false; //aStudent is already null
}
Run Code Online (Sandbox Code Playgroud)

这样它就是你改变的外部指针,而不是本地副本.

  • @IanLing除非你像我的例子中那样传入一个指针引用,否则它是不可能的.但是,您可以进行我建议的更改,并且它会"破坏调用它的代码".我的意思是传入一个引用对于调用它的代码是透明的. (2认同)