构造器通过抛出异常完成?是否有内存泄漏? [英] Constructor finishes by throwing an exception ? Is there a memory leak?

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

问题描述

我正在浏览这篇文章

I was going over this article and it states


注意:如果一个构造函数抛出一个异常结束,与对象本身相关联的内存
将被清除 - 是没有内存
泄漏。例如:

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
}


$ b b

我很难理解这一点,如果有人能够澄清这一点,我将不胜感激。我试过下面的例子,它显示在构造函数内部的异常不会被调用。

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

如何解决此问题?

对于由此造成的不便,我们深表歉意。

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.

$ c> 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天全站免登陆