如何使用析构函数删除在 Class 构造函数中分配的动态内存

How to Delete Dynamic Memory allocated in Class Constructor using destructor

我正在尝试使用析构函数释放对象的内存。该内存是在对象声明时分配的。下面的代码片段是我正在制作的程序的综合版本,但它解释了我的问题。 我知道问题出在通过析构函数解除分配时,但我不知道可能是什么原因导致了异常。

#include <iostream>
using namespace std;
class student 
{
private:
    char const* firstname;
    char const* lastname;
public:
    student()
    {
        firstname = new char[10];
        lastname = new char[10];
        firstname = "HelloMaria";
        lastname = "Something";
    }
    void print()
    {
        cout << "Firstname =  " << firstname<<endl;
        cout << "Last name = " << lastname << endl;
    }
    ~student()
    {
        cout << "Destructor Called" << endl;
        delete[] firstname;
        delete[] lastname;
    }
};
int main()
{
    student obj1;
    obj1.print();
    system("pause");
    return 0;

}

你的问题在这几行:

    firstname = new char[10];
    lastname = new char[10];
    firstname = "HelloMaria";
    lastname = "SomethingVe";

首先你将 firstnamelastname 都设置为指向新分配的 char 数组,这很好......但是你立即将它们更改为指向静态分配字符串代替。这意味着当您在析构函数中将指针传递给 delete[] 时,您正在尝试删除您从未分配的字符串,这会调用未定义的行为。

处理字符串的正确方法是使用 std::string 而不是分配您自己的字符缓冲区,但是如果由于某种原因您不能这样做,那么下一个最好的方法是你正在尝试做的会更像这样:

student()
{
    firstname = alloc_string_buffer("HelloMaria");
    lastname = alloc_string_buffer("SomethingVe");
}

private:
   // Helper function to allocate the right-sized char-buffer and 
   // copy the bytes from the passed-in literal string into the buffer
   char * alloc_string_buffer(const char * s)
   {
       size_t numBytesToAllocate = strlen(s)+1;  // +1 for the NUL terminator byte
       char * buf = new char[numBytesToAllocate];
       strcpy(buf, s);
       return buf;
   }