从构造函数抛出异常 [英] Throwing exceptions from constructors

查看:142
本文介绍了从构造函数抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与同事讨论关于从构造函数抛出异常的问题,我想要一些反馈。



是否可以抛出异常构造函数,从设计的角度?



假设我在一个类中包装一个posix mutex,它看起来像这样:



> class Mutex {
public:
Mutex(){
if(pthread_mutex_init(& mutex_,0)! = 0){
throw MutexInitException();
}
}

〜Mutex(){
pthread_mutex_destroy(& mutex_);
}

void lock(){
if(pthread_mutex_lock(& mutex_)!= 0){
throw MutexLockException
}
}

void unlock(){
if(pthread_mutex_unlock(& mutex_)!= 0){
throw MutexUnlockException
}
}

private:
pthread_mutex_t mutex_;
};

我的问题是,这是标准的做法吗?因为如果pthread mutex_init调用失败,互斥对象是不可用的,所以抛出异常确保不会创建互斥。



我应该创建一个成员函数init Mutex类并调用pthread mutex_init,在其中将返回一个基于pthread的bool mutex_init的返回?这种方式我不必为这样的低级对象使用异常。

解决方案

是的,构造函数是这样做的标准方式。有关详细信息,请参阅有关处理失败的构造函数的常见问题。有一个init()方法也可以工作,但是每个创建mutex对象的人都必须记住必须调用init()。我认为这违反了 RAII 原则。


I'm having a debate with a co-worker about throwing exceptions from constructors, and thought I would like some feedback.

Is it ok to throw exceptions from constructors, from a design point of view?

Lets say I'm wrapping a posix mutex in a class, it would look something like this:

class Mutex {
public:
  Mutex() {
    if (pthread_mutex_init(&mutex_, 0) != 0) {
      throw MutexInitException();
    }
  }

  ~Mutex() {
    pthread_mutex_destroy(&mutex_);
  }

  void lock() {
    if (pthread_mutex_lock(&mutex_) != 0) {
      throw MutexLockException();
    }
  }

  void unlock() {
    if (pthread_mutex_unlock(&mutex_) != 0) {
      throw MutexUnlockException();
    }
  }

private:
  pthread_mutex_t mutex_;
};

My question is, is this the standard way to do it? Because if the pthread mutex_init call fails the mutex object is unusable so throwing an exception ensures that the mutex won't be created.

Should I rather create a member function init for the Mutex class and call pthread mutex_init within which would return a bool based on pthread mutex_init's return? This way I don't have to use exceptions for such a low level object.

解决方案

Yes, throwing an exception from the failed constructor is the standard way of doing this. Read this FAQ about Handling a constructor that fails for more information. Having a init() method will also work, but everybody who creates the object of mutex has to remember that init() has to be called. I feel it goes against the RAII principle.

这篇关于从构造函数抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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