Mil*_*avi 5 c++ memory-leaks dynamic-memory-allocation unique-ptr
在C ++中如何编程有一段说:
一种常见的编程习惯是分配动态内存,将该内存的地址分配给指针,使用指针操作内存,并在不再需要内存时使用delete取消分配内存.如果在成功分配内存之后但在执行delete语句之前发生异常,则可能发生内存泄漏.C++标准在头文件中提供了类模板unique_ptr来处理这种情况.
任何关于可以给我一个真实的例子,异常发生和内存将泄漏像这篇文章?
jro*_*rok 11
一个更微妙的例子.
对包含两个动态分配的数组的类进行简单的实现:
struct Foo {
private:
int* first;
int* second;
public:
Foo()
: first(new int[10000])
, second(new int[10000])
{ }
void Bar() { throw 42; }
~Foo()
{
delete [] first;
delete [] second;
}
};
int main()
{
Foo f;
/* more code */
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我们得到一个异常,因为我们在Bar某个地方调用方法,一切都很好 - 堆栈展开得到f的析构函数被调用.
但是如果我们bad_alloc在初始化时得到一个,那么我们会second泄漏first指向的内存.
void func()
{
char *p = new char[10];
some_function_which_may_throw(p);
delete [] p;
}
Run Code Online (Sandbox Code Playgroud)
如果调用some_function_which_may_throw(p)抛出异常,我们会泄漏指向的内存p.
class MyClass
{
public:
char* buffer;
MyClass(bool throwException)
{
buffer = new char[1024];
if(throwException)
throw std::runtime_error("MyClass::MyClass() failed");
}
~MyClass()
{
delete[] buffer;
}
};
Run Code Online (Sandbox Code Playgroud)
int main()
{
// Memory leak, if an exception is thrown before a delete
MyClass* ptr = new MyClass(false);
throw std::runtime_error("<any error>");
delete ptr;
}
Run Code Online (Sandbox Code Playgroud)
int main()
{
// Memory leak due to a missing call to MyClass()::~MyClass()
// in case MyClass()::MyClass() throws an exception.
MyClass instance = MyClass(true);
}
Run Code Online (Sandbox Code Playgroud)
另请参阅:C++:如果构造函数可能抛出异常,则处理资源(参考FAQ 17.4)