假设我有一个这样定义的调试函数:
namespace debug {
void report(std::string message);
}
我能否使用一些编译器技巧,在编译时将每个调用安全地替换为 nop
。我不想调用一个空函数,我不想调用这个函数。
如果可能的话……我也可以让命名空间“消失”吗?
调试可执行文件将使用定义的符号 DEBUGEXECUTABLE
进行编译(我可以想象一些宏的技巧)。
最佳答案
你可以这样做:
namespace debug
{
void report(std::string message); // ToDo - define this somewhere
}
namespace release
{
template <class Y>
void report(Y&&){} // Intentionally do nothing
}
#if defined(DEBUGEXECUTABLE)
namespace foo = debug; // set foo to the debug namespace
#else
namespace foo = release; // set foo to the release namespace
#endif
然后在您的代码中使用foo::report
。我喜欢这样,因为它最大限度地减少了预处理器宏的使用,并使调试和发布配置中的任何编译器错误大致相似。
在 Release模式下传递一个 r-value 引用 将允许编译器优化任何匿名临时对象。对于调试系列函数,您应该通过常量引用传递字符串,以避免任何可能的值复制:void report(const std::string& message);
关于c++ - 某些情况下 "disappears"的调试功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27298570/