在C++中取消调试函数的更好方法
Better way to nullify debug functions in C++
我的程序使用了许多#ifdef _DEBUG_ ... #endif
块,以取消发布版本的调试功能。
然而,它会阻塞代码,并使代码读起来不愉快。
有更好的方法吗?
我可以想到的一种方法是通过将函数定义为空来取消它,例如:
#ifdef _DEBUG_
void foo(int bar)
{
do_somthing();
}
#else
#define foo(a) do {; } while(0)
#endif
所以我们只有一个#ifdef _DEBUG_ ... #endif
。所有调用foo()
的地方,我们不必添加#ifdef _DEBUG_ ... #endif
。
然而,也有例外:
- 当调试函数有返回值时,上述策略将不起作用。例如,调用函数的代码可能是以下模式:
bar = foo();
- 同样,当调试函数是类的成员函数形式时,上述策略将不起作用
知道吗?
把#ifdef移到函数本身中怎么样?即
// In a .h file somewhere...
inline int foo(int bar)
{
#ifdef DEBUG
return do_something();
#else
(void) bar; // this is only here to prevent a compiler warning
return 1; // or whatever trivial value should be returned when not debugging
#endif
}
只要函数可以内联(即,只要函数体在头文件中),编译器就会在非DEBUG的情况下对其进行优化,因此这样做在非调试构建中不应该有任何额外的开销。
如果函数太大而无法正常内联,Jeremy的解决方案将不起作用,您仍然需要这两个定义。
// In .h file
#ifndef NDEBUG
int foo(int bar); // Definition in .cpp file
#else
inline int foo(int) {
return 42;
}
#endif
注意,根据assert
约定,NDEBUG
是为发布版本定义的。
相关文章:
- 初始化具有非默认构造函数的std::数组项的更好方法
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 编写按初始值循环的循环的更好方法是什么
- 用 c++ 为游戏制作"bullet"的更好方法?
- 在CMakeLists中包含目录的更好方法.txt
- 将QDomDocument数据用作文本的更好方法
- C++ - 创建具有相同字符的特定大小的以 null 结尾的 c 样式字符串的更好方法
- 在 sqlite3 中批量插入的更好方法C++
- 设计许多单例代码结构的更好方法
- 使用继承的类模板避免公共成员不可见和源代码膨胀/重复的更好方法
- 在初始化列表中初始化数组的更好方法
- 将对象从一个 std::d eque 移动到另一个的更好方法
- 请告诉我在巴泽尔拥有多平台工作空间的更好方法
- 构造具有大量数据的对象的更好方法(C++)
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 在C++中创建不可变对象的更好方法
- 在构造函数中组织初始值设定项列表的更好方法
- std::copy with return values - 防止"expression: string iterators incompatible"的更好方法?
- 删除数组成员的更好方法是什么?
- 在C 中操作数据的更好方法是什么