【发布时间】:2016-10-25 15:06:42
【问题描述】:
我有以下类,我以二进制模式保存在文件中:
class lol
{
public:
~lol() {
std::cout << "destucted" << std::endl;
system("pause");
}
int age;
std::string name;
};
现在我主要有这个:
int main()
{
{
lol kar;
kar.age = 17;
kar.name = "Blabla";
ytxt("class").Write(std::string((char*)&kar, sizeof(kar))); //Saves the class in binary mode
}
lol * asd;
{
std::string stClass = ytxt("class").Read();//reads the file in binary
asd = (lol*)new char[stClass.length()];//asd is now allocated with new
memcpy_s(asd, stClass.length(), stClass.c_str(), stClass.length());//copy the content of the file into the class
}
std::cout << "Name: " << asd->name << std::endl;//output
std::cout << "Age: " << asd->age << std::endl;
asd->age = 79;
std::cout << "Age: " << asd->age << std::endl;
delete asd;//I cannot delete it as lol
//delete (char*)asd;//works but lol destructor is not called
system("pause");
}
asd 指针的内容正在打印到控制台,指针被删除并调用析构函数。最后抛出异常。
当我不删除 asd 指针时,一切正常,但不调用 asd 指针的析构函数。我知道指针被分配为new char,我必须将它作为new char 删除,但是还有另一种方法可以让删除操作调用lol 的析构函数吗?
【问题讨论】:
-
什么是
ytxt。它是否正确序列化字符串?或者只是转储指针。 -
为什么将对象创建为
new char[stClass.length()]而不是new lol()? -
这将最终加入数百个类似问题的行列,其中有人试图简单地对非 POD 类型进行 blob 管理。可悲的是,这样做的尝试在措辞、标题和代码示例上大相径庭,几乎不可能在这数百个重复项中找到一个。