在初始化列表中抛出异常?

6 c++ methods class

我有以下代码:

在 Game.h 中:

mtm::Dimensions dimensions;
std::vector<std::shared_ptr<Character>> board;
Run Code Online (Sandbox Code Playgroud)

在 Game.cpp 中:

Game::Game(int height, int width) : dimensions(height, width), board(height * width, nullptr) 
{
    if (height <= 0 || width <= 0) {
        throw mtm::IllegalArgument();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是您可能会注意到,我抛出错误为时已晚,如果height * width小于 0,则将抛出 bad_alloc 而不是IllegalArgument,我该如何解决这个问题?

有没有办法在初始化列表中抛出异常?

for*_*818 4

如果您无法进行签入mtm::Dimensions,它确实应该在那里,您可以使用辅助函数:

int throw_if_not_positive(int x) {
    if (x <= 0) throw mtm::IllegalArgument();
    return x;
}

Game::Game(int height, int width) : 
    dimensions(throw_if_not_positive(height),
               throw_if_not_positive(width)), 
    board(height * width, nullptr) 
{
}
Run Code Online (Sandbox Code Playgroud)

或使用unsigned,或使用

struct positive_int {
     int value;
     positive_int(int x) : value(x) {
        if (x <= 0)  throw mtm::IllegalArgument();
     }
     operator int(){ return value; }
};

Game::Game(positive_int height, positive_int width) : 
    dimensions(height,width), 
    board(height * width, nullptr) 
{
}
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个的是它在“维度”之前捕获错误,因此它会提前失败,而不会浪费精力构建维度。 (2认同)