tau*_*ran 41 c++ debugging logging assert
喂!
我正在寻找一种方法来添加自定义消息来断言语句.我发现这个问题在断言中添加自定义消息?但那里的信息是静态的.我想做这样的事情:
assert((0 < x) && (x < 10), std::string("x was ") + myToString(x));
Run Code Online (Sandbox Code Playgroud)
当断言失败时,我想要正常输出加上例如"x为100".
Kon*_*lph 70
你在这里运气不好.最好的方法是定义自己的assert宏.
基本上,它看起来像这样:
#ifndef NDEBUG
# define ASSERT(condition, message) \
do { \
if (! (condition)) { \
std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
<< " line " << __LINE__ << ": " << message << std::endl; \
std::terminate(); \
} \
} while (false)
#else
# define ASSERT(condition, message) do { } while (false)
#endif
Run Code Online (Sandbox Code Playgroud)
这将定义ASSERT只有在没有调试宏宏NDEBUG没有定义.
然后你会像这样使用它:
ASSERT((0 < x) && (x < 10), "x was " << x);
Run Code Online (Sandbox Code Playgroud)
这比您的使用简单一点,因为您不需要字符串化"x was "和x显式,这是由宏隐式完成的.
Cam*_*ron 17
在没有编写自己的例程的情况下,有一些旧技巧可以包含消息:
首先是:
bool testbool = false;
assert(("this is the time", testbool));
Run Code Online (Sandbox Code Playgroud)
还有:
bool testbool = false;
assert(testbool && "This is a message");
Run Code Online (Sandbox Code Playgroud)
第一个起作用,因为内部parens表达式结果是'testbool'的值.第二个工作,因为字符串的值将是非零.
更好的选择是教导调试器在失败时停止断言,然后您不仅可以检查x值,还可以检查包括调用堆栈在内的任何其他信息.也许,这就是你真正想要的.这里提到了示例实现方法向您的共同程序员展示在C++编程时某些方法尚未在类中实现
#define ASSERT_WITH_MESSAGE(condition, message) do { \
if (!(condition)) { printf((message)); } \
assert ((condition)); } while(false)
Run Code Online (Sandbox Code Playgroud)
扩展康德拉德·鲁道夫的回答:
#include <iostream>
#ifdef NDEBUG
#define assert(condition, message) 0
#else
#define assert(condition, message)\
(!(condition)) ?\
(std::cerr << "Assertion failed: (" << #condition << "), "\
<< "function " << __FUNCTION__\
<< ", file " << __FILE__\
<< ", line " << __LINE__ << "."\
<< std::endl << message << std::endl, abort(), 0) : 1
#endif
void foo() {
int sum = 0;
assert((sum = 1 + 1) == 3, "got sum of " << sum << ", but expected 3");
}
int main () {
foo();
}
Run Code Online (Sandbox Code Playgroud)
输出是...
Assertion failed: ((sum = 1 + 1) == 3), function foo, file foo.cpp, line 13.
got sum of 2, but expected 3
zsh: abort ./a.out
Run Code Online (Sandbox Code Playgroud)
这类似于 std::assert 宏在我的系统上输出的内容,只是带有附加的用户定义消息
| 归档时间: |
|
| 查看次数: |
36763 次 |
| 最近记录: |