【问题标题】:Better way to nullify debug functions in C++在 C++ 中取消调试函数的更好方法
【发布时间】:2015-11-13 02:27:03
【问题描述】:

我的程序使用了许多 #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

但是,也有例外:

  1. 当调试函数有返回值时,上述策略将不起作用。例如调用函数的代码可能是这种模式:bar = foo();
  2. 当调试函数是类的成员函数形式时,同样,上述策略将不起作用。

有什么想法吗?

【问题讨论】:

标签: c++


【解决方案1】:

将#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
}

...只要函数可以内联(即只要函数体在头文件中),编译器将在非调试情况下对其进行优化,所以不应该有任何这样做会导致非调试版本的额外开销。

【讨论】:

    【解决方案2】:

    如果函数太大而无法正常内联,Jeremy 的解决方案将不起作用,您仍然需要这两个定义。

    // In .h file
    #ifndef NDEBUG
    int foo(int bar); // Definition in .cpp file
    #else
    inline int foo(int) {
        return 42;
    }
    #endif
    

    请注意,根据assert 约定,NDEBUG 是为发布版本定义的。

    【讨论】:

    • 如果内联函数太大,只创建一个非内联辅助函数并在必要时调用内联函数可能会更干净。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 2014-03-25
    相关资源
    最近更新 更多