问题描述
我正在尝试使用析构函数释放对象的内存。该内存是在对象声明时分配的。下面的代码片段是我正在制作的程序的综合版本,但它解释了我的问题。 我知道问题是通过析构函数解除分配,但我不知道可能是什么原因导致异常。
#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";
首先,您将 firstname
和 lastname
都设置为指向新分配的 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;
}