C ++:如果构造函数可能抛出异常,处理资源(参考FAQ 17.4) [英] C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]

查看:137
本文介绍了C ++:如果构造函数可能抛出异常,处理资源(参考FAQ 17.4)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢所有回复。

我重新格式化了我的问题,以便在containg类构造函数抛出异常后了解成员指针的状态

I reformatted my question to understand the state of the member pointer after the containg class constructor throws an exception

再次我的示例类:)

class Foo
{
public:
    Foo()
    {
       int error = 0;
        p = new Fred;

        throw error;  // Force throw , trying to understand what will happen to p
    }

   ~Foo()
    {
       if (p)
       {
           delete p;
           p = 0;
       }
     }
private:
   Fred* p;
};

int main()
{
      try
      {
         Foo* lptr = new Foo;
      }
      catch (...)
      {}
}

类foo的consturctor会为某些随机原因抛出异常。我知道foo的desturctor永远不会被调用,但在这种情况下,p的析构函数被调用。

The consturctor for class foo would throw an exception for some random reason. I understand that the desturctor of foo will never be called but in this case will the destructor for p get called?

它有什么区别,它有p作为一个智能指针

what difference it makes to have p as a boost smart pointer than a raw pointer to fred.

感谢。

推荐答案

是这里的类似问题

There is a similar question here that covers what your asking.

在这种情况下,如果调用 new 失败,该指针保证被释放。如果调用成功,并且构造函数抛出后,你将有一个内存泄漏。

In this case, if the call to new fails, then the memory for the pointer is guaranteed to be freed. If the call succeeds, and the constructor throws after that, you will have a memory leak.

类的析构函数不会被调用,因为对象从未完全建。有两种方法可以解决此问题。

The destructor of the class will not be called, because the object was never fully constructed. There are two ways to fix this.

1)

在构造函数中完全管理异常:

Have exceptions fully managed in the constructor:

class Foo
{
public:
    Foo()
    try
    {
        p = new p;

        throw /* something */; 
    }
    catch (...)
    {
       delete p;

       throw; //rethrow. no memory leak
    }
private:
    int *p;
};

2)

指针。当输入构造函数时,它的所有成员都被构造。并且因为当一个构造函数抛出,并且构造了对象成员时,它们必须被销毁。而一个智能指针修复了:

Or use a smart pointer. When a constructor is entered, all of its members have been constructed. And because when a constructor throws, and objects members have been constructed, they must be destructed. And a smart pointer fixes that:

class Foo
{
public:
    Foo() :
    p(new int)
    {
        throw /* something */; 
    }
private:
    std::auto_ptr<int> p;
};

这篇关于C ++:如果构造函数可能抛出异常,处理资源(参考FAQ 17.4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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