gpt4 book ai didi

c++ - C++ 中的内存泄漏示例(通过使用异常)

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:49:40 25 4
gpt4 key购买 nike

在 C 中 ++ How to program有一段说:

A common programming practice is to allocate dynamic memory, assign the address of that memory to a pointer, use the pointer to manipulate the memory and deallocate the memory with delete when the memory is no longer needed. If an exception occurs after successful memory allocation but before the delete statement executes, a memory leak could occur. The C++ standard provides class template unique_ptr in header to deal with this situation.

任何人都可以给我介绍一个发生异常和内存泄漏的真实例子like this post

最佳答案

一个更微妙的例子。

采用包含两个动态分配数组的类的简单实现:

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 */
}

现在,如果我们因为在某处调用方法 Bar 而出现异常,一切都很好 - 堆栈展开保证 f 的析构函数被调用。

但是,如果我们在初始化 second 时得到一个 bad_alloc,我们就会泄漏 first 指向的内存。

关于c++ - C++ 中的内存泄漏示例(通过使用异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15372242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com