如果构造函数抛出,由`new`分配的内存会发生什么? [英] What happens to the memory allocated by `new` if the constructor throws?

查看:156
本文介绍了如果构造函数抛出,由`new`分配的内存会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码会导致内存泄漏吗?

Will this code cause a memory leak?

#include <stdexept>

class MyClass
{
public:
    MyClass()
    {
        throw std::runtime_error("Test");
    }
};

int main()
{
    try
    {
        MyClass * myClass = new MyClass;
    }
    catch (const std::exception & exc)
    {
        // Memory leak?
    }
    return 0;
}

new 从不删除。这是内部处理,还是实际的内存泄漏?

The memory allocated by new is never deleted. Is this taken care of internally, or it an actual memory leak?

推荐答案

内存将在异常传播之前自动释放。

The memory will be automatically freed before the exception propagates.

这是至关重要的,因为a)程序从来没有收到指向free的指针,b)即使是这样,它也没有可移植的方法来释放它,因为内存从未成为可以删除的对象。

This is essential, because a) the program never receives a pointer to free, and b) even if it did, it would have no portable way to actually free it since the memory never became an object that you can delete.

这篇关于如果构造函数抛出,由`new`分配的内存会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆