本文已参与「新人创作礼」活动,一起开启掘金创作之路。
QtApplets-Q_ASSERT使用
今天又学习了一个知识点,Q_ASSERT,神奇的宏,这个只有在**Debug**模式下才会生效的。主要功能就是在我们需要的位置使用该宏,在程序出错的地方,就会直接告诉我们出错的位置,对于大型项目来说,兼职就是Debug利器。
QtApplets-Q_ASSERT使用1 Q_ASSERT2 Q_ASSERT_X3 二者对比4 特别注意4 参考链接☞ 源码
关键字:
Q_ASSERT_X、调试、断言、Q_ASSERT、QT_NO_DEBUG
1 Q_ASSERT
先看第一个Q_ASSERT源码如下:
Q_CORE_EXPORT void qt_assert(const char *assertion, const char *file, int line) noexcept;
#if !defined(Q_ASSERT)
# if defined(QT_NO_DEBUG) && !defined(QT_FORCE_ASSERTS)
# define Q_ASSERT(cond) static_cast<void>(false && (cond))
# else
# define Q_ASSERT(cond) ((cond) ? static_cast<void>(0) : qt_assert(#cond, __FILE__, __LINE__))
# endif
#endif
void Q_ASSERT(bool test)当表达式为false是,打印出警告信息。测试代码如下
void MainWindow::on_pushButton_clicked()
{
int a = 1;
int b = 2;
int c = a + b;
Q_ASSERT(c == 5);
qDebug() << "Test 1";
}
演示效果如下:
2 Q_ASSERT_X
Q_ASSERT_X源码如下:
Q_CORE_EXPORT void qt_assert_x(const char *where, const char *what, const char *file, int line) noexcept;
#if !defined(Q_ASSERT_X)
# if defined(QT_NO_DEBUG) && !defined(QT_FORCE_ASSERTS)
# define Q_ASSERT_X(cond, where, what) static_cast<void>(false && (cond))
# else
# define Q_ASSERT_X(cond, where, what) ((cond) ? static_cast<void>(0) : qt_assert_x(where, what, __FILE__, __LINE__))
# endif
#endif
void Q_ASSERT_X(bool test, const char *where, const char *what)当test为false是,打印警告信息,并包含自定义信息,示例代码如下:
void MainWindow::on_pushButton_2_clicked()
{
int a = 1;
int b = 2;
int c = a + b;
Q_ASSERT_X(c == 5,"Error","Error Test 1");
qDebug() << "Test 1";
}
演示效果如下:
3 二者对比
这两个宏都是在我们传入的值为false的时候触发,都会打印信息,只是Q_ASSERT_X支持打印我们自定义的信息。
4 特别注意
不论是Q_ASSERT也好Q_ASSERT_X也罢,都是在Debug才生效的,在Release版本中,将被自动优化掉如下图所所示

4 参考链接
搬运链接:
☞ 源码
源码链接:GitHub仓库自取
使用方法:☟☟☟