我一直在学习 OpenCV 教程,偶然发现了 assert
函数;它有什么作用?
最佳答案
assert
如果其参数为假,将终止程序(通常带有引用断言语句的消息)。常用于调试时,让程序在出现意外情况时更明显地失败。
例如:
assert(length >= 0); // die if length is negative.
您还可以添加一条信息更丰富的消息,以在失败时显示,如下所示:
assert(length >= 0 && "Whoops, length can't possibly be negative! (didn't we just check 10 lines ago?) Tell jsmith");
或者像这样:
assert(("Length can't possibly be negative! Tell jsmith", length >= 0));
当您进行发布(非调试)构建时,您还可以通过定义 NDEBUG
宏来消除评估 assert
语句的开销,通常使用编译器开关。这样做的必然结果是您的程序应该从不依赖断言宏运行。
// BAD
assert(x++);
// GOOD
assert(x);
x++;
// Watch out! Depends on the function:
assert(foo());
// Here's a safer way:
int ret = foo();
assert(ret);
结合程序调用 abort() 并且不保证做任何事情,断言应该只用于测试开发人员假设的事情,而不是,例如,用户输入数字而不是字母 (应该通过其他方式处理)。
关于c++ - "assert"函数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1571340/