gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:57:09 27 4
gpt4 key购买 nike

我有以下代码:
在 Game.h 中:

mtm::Dimensions dimensions;
std::vector<std::shared_ptr<Character>> board;
在 Game.cpp 中:
Game::Game(int height, int width) : dimensions(height, width), board(height * width, nullptr) 
{
if (height <= 0 || width <= 0) {
throw mtm::IllegalArgument();
}
}
但是您可能会注意到,如果 height * width,我抛出错误为时已晚。小于 0 则将抛出 bad_alloc 而不是 IllegalArgument , 我该如何解决这个问题?
有没有办法在初始化列表中抛出异常?

最佳答案

如果您无法在 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)
{
}
或使用 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)
{
}

关于c++ - 在初始化列表中抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62604262/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com