c++ - 构造函数通过抛出异常结束?是否存在内存泄漏?

标签 c++ exception memory-leaks constructor

我正在检查 this文章 它指出

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
}

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

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

我该如何解决这个问题?

对于更新可能造成的不便,我们深表歉意。

最佳答案

"... the destructor would not be called."

由于对象还未被视为已构造,在构造函数因异常而失败后,将不会调用析构函数。

对象分配和构造(仅仅是销毁)是不同的事情。

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

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.

而是为来自 standard dynamic memory management library 的类成员使用合适的智能指针.

关于c++ - 构造函数通过抛出异常结束?是否存在内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25962716/

相关文章:

java.text.ParseException : Unparseable date "yyyy-MM-dd' T'HH:mm:ss. SSSZ"- SimpleDateFormat

Python 2.5 作为关键字有多个异常(exception)

c++ - 按值返回堆栈中的对象

android - 服务com.google.android.youtube.api.service.YouTubeService泄漏了IntentReceiver uds @ 5fa5135

iPhone 开发 : How to Catch Exception/NSError in Objective-C?

javascript - 为什么这个 javascript 在 Chrome 中有内存泄漏?

c# - 如何正确地将多个 cv::Mat 从 c++ dll 传递到 opencvsharp Mat c#?

c++ - Matlab 到 C++ 代码转换

c++ - 使用 mingw 在 windows 上编译 libnoise

c++ - 概念难度 c++ Deck of Cards