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

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

问题描述

我正在与一名同事辩论一下关于从构造函数中抛出异常的想法,并认为我想要一些反馈。

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?

说我在一个类中包装一个posix互斥体,它看起来像这样:

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

我的问题是,这是标准的做法吗?因为如果pthread mutex_init调用失败,则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.

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

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.

推荐答案

是的,从失败中抛出异常构造函数是这样做的标准方法。请阅读有关处理失败的构造函数以获取更多信息的常见问题。拥有一个init()方法也可以起作用,但创建互斥体对象的每个人都必须记住必须调用init()。我觉得违反 RAII 原则。

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