构造函数以抛出异常结束?是否存在内存泄漏? [英] Constructor finishes by throwing an exception ? Is there a memory leak?

查看:24
本文介绍了构造函数以抛出异常结束?是否存在内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读这篇它指出

注意:如果构造函数以抛出异常结束,内存与对象本身相关联的被清理——没有内存泄漏.例如:

Note: if a constructor finishes by throwing an exception, the memory associated with the object itself is cleaned up — there is no memory leak. For example:

void f()
{
X x; // If X::X() throws, the memory for x itself will not leak
Y* p = new Y(); // If Y::Y() throws, the memory for *p itself will not leak
}

我很难理解这一点,如果有人能澄清这一点,我将不胜感激.我尝试了以下示例,该示例表明构造函数中发生异常时不会调用析构函数.

I am having difficulty understanding this and would appreciate it if someone could clarify this. I tried the following example which shows that incase of an exception inside a constructor the destructor would not be called.

struct someObject
{
    someObject()
    {
      f = new foo();    
      throw 12;
    }
    ~someObject()
    {
        std::cout << "Destructor of someobject called";
    }

    foo* f;
};

class foo
{
public:
    foo()
    {
            g = new glue();
            someObject a;
    }
    ~foo()
    {
        std::cout << "Destructor of foo";
    }
 private:
  glue* g;
};


int main()
{
    try
    {
        foo a;
    }
    catch(int a)
    {
        //Exception caught. foo destructor not called and someobject destrucotr not called.
       //Memory leak of glue and foo objects
    }
}

我该如何解决这个问题?

How would I fix this issue ?

对于更新可能给您带来的不便,我们深表歉意.

Sorry for the inconvenience the update might have caused.

推荐答案

...不会调用析构函数."

由于对象还没有被认为是已构造的,所以在构造函数因异常而失败后,不会调用析构函数.

Since the object isn't considered as constructed yet, after the constructor failed with an exception, the destructor won't be called.

对象分配和构造(只是销毁)是不同的东西.

Object allocation, and construction (merely destruction) are different things.

在抛出异常之前使用 new() 分配的任何对象都会泄漏.

Any objects allocated using new() before the exception is thrown will leak.

您不应该自己管理这些资源,除非您真的、真的、真的需要它,并且大约 100% 确定自己在做什么.

You shouldn't manage these resources yourself, unless you're really, really, really need it, and are about 100% sure about what you're doing.

而是为来自标准动态内存管理库的类成员使用合适的智能指针.

Rather use suitable smart pointers for class members from the standard dynamic memory management library.

这篇关于构造函数以抛出异常结束?是否存在内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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