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

查看:112
本文介绍了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的守护者永远不会被调用,但在这种情况下,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作为一个提升智能指针比起fred的原始指针。

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

谢谢。

推荐答案

类似的问题在这里

在这种情况下,如果调用失败,那么内存为指针被保证被释放。如果调用成功,并且构造函数抛出之后,将会有内存泄漏。

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)

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

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