我一直在学习 OpenCV 教程并遇到了这个assert功能;它有什么作用?
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));
当您进行发布(非调试)构建时,您还可以assert通过定义宏来消除评估语句的开销NDEBUG,通常使用编译器开关。这样做的必然结果是你的程序 永远不 应该依赖断言宏的运行。
NDEBUG
// 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() 并且不保证做任何事情的组合来看,断言应该只用于测试开发人员假设的事情,而不是,例如,用户输入数字而不是字母(应该是其他方式处理)。