释放用户定义表达式析构函数中的动态内存
Freeing dynamic memory in user defined exeption's destructor
我正在尝试删除用户定义异常的析构函数中的动态内存,该内存是在用户定义异常构造函数中分配的。但我得到的核心转储声明内存被释放了两次:
user1@ubuntu:~/practice$ ./a.out
Test Exception
*** Error in `./a.out': double free or corruption (fasttop): 0x0000000000f0b0b0 ***
Aborted (core dumped)
我怀疑MyException
对象两次超出范围,一次在myfunc()
中,另一次在main的catch
块中,这导致了此问题。但我不知道在这种情况下如何释放内存。你能帮我吗?
这是代码:
#include<iostream>
#include<exception>
#include<cstring>
using namespace std;
class MyException: public exception
{
char *msg;
public:
MyException(){}
MyException(char *str)
{
msg = new char[strlen(str)+1];
strcpy(msg,str);
}
char *what()
{
return msg;
}
~MyException() throw()
{
delete msg;
}
};
class A
{
public:
void myfunc() throw(MyException)
{
throw MyException((char*)"Test Exception");
}
};
int main()
{
try
{
A ob;
ob.myfunc();
}
catch (MyException e)
{
cout<<e.what()<<endl;
}
}
问题是通过遵循三条规则来解决的。什么是"三条规则"?
来自另一个SO答案:
如果您需要自己显式声明析构函数、复制构造函数或复制赋值运算符,则可能需要显式声明这三个运算符。
更多详细信息,请参阅另一个SO问题和维基百科。
#include <iostream>
#include <exception>
#include <cstring>
using namespace std;
class MyException: public exception
{
char *msg;
public:
MyException(const char *str) // Making the constructor take a `const char*`
// so it can be invoked with a string
// literal
{
msg = new char[strlen(str)+1];
strcpy(msg,str);
}
MyException(MyException const& copy)
{
msg = new char[strlen(copy.msg)+1];
strcpy(msg,copy.msg);
}
char const* what() const // Making the return type 'const char*' and
// making the member function a const. That's
// necessary to make it an override of
// std::exception::what()
{
return msg;
}
~MyException() throw()
{
delete msg;
}
MyException& operator=(MyException const& rhs)
{
if ( this != &rhs )
{
delete [] msg;
msg = new char[strlen(rhs.msg)+1];
strcpy(msg,rhs.msg);
}
return *this;
}
};
class A
{
public:
void myfunc() throw(MyException)
{
throw MyException((char*)"Test Exception");
}
};
int main()
{
try
{
A ob;
ob.myfunc();
}
catch (MyException e)
{
cout<<e.what()<<endl;
}
}
输出:
测试异常
相关文章:
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 开放 CV 中的动态内存分配,用于视频处理
- 为什么类和 main() 函数中也有动态内存分配
- 在没有动态内存的世界中,我是否需要虚拟析构函数?
- c++ 动态内存 堆栈中的分配
- 给定特定内存地址的数组的动态内存分配
- 释放动态内存时C++错误
- 我刚刚了解了C++中的动态内存分配
- 无法删除布尔动态内存分配
- 有没有办法找到动态内存大小,比如大小?
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 具有对齐存储的动态内存分配
- 指向数组unique_ptr在调用 release() 后会自动释放动态内存,这是真的吗?
- 在cpp中使用boost-python的python代码是否进行动态内存分配
- 我应该在这个程序中使用静态内存分配还是动态内存分配
- C++ 模板函数中的动态内存分配
- 指向动态内存中结构中的变量时出现问题
- C++具有动态内存分配的 constexpr 函数
- 动态内存分配错误
- 按引用传递和动态内存分配之间的区别是什么