gpt4 book ai didi

c++ - 在类修改器中使用 assert() 是好的做法吗?

转载 作者:行者123 更新时间:2023-11-30 01:00:11 25 4
gpt4 key购买 nike

例如:

void Date::month(unsigned int inMonth) {
assert(inMonth <= 12);
_month = inMonth;
}

如果这不是好的做法,那么正确的做法是什么?

最佳答案

您不应使用断言来确保public 成员函数的参数有效。原因是您的类的客户无法以任何有意义的方式对失败的断言使用react(从发布版本中删除断言的事实也无济于事)。

根据经验,断言只能用于您严格控制的事物(例如,私有(private)方法的参数)。

在这种情况下,你最好抛出 std::invalid_argument异常:

void Date::month(unsigned int month) 
{
if(month == 0 || month > 12)
{
throw std::invalid_argument("a month must be in the [1-12] range");
}
_month = month;
}

关于c++ - 在类修改器中使用 assert() 是好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3031198/

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