Glog剖析之DLOG

来源:互联网 发布:linux mplayer 缩小 编辑:程序博客网 时间:2024/06/05 22:55

首先来看看Glog文档上是如何介绍DLOG的:

Debug Mode Support


Special "debug mode" logging macros only have an effect in debug mode and are compiled away to nothing for non-debug mode compiles. Use these macros to avoid slowing down your production application due to excessive logging.


   DLOG(INFO) << "Found cookies";



下来来看看DLOG宏是如何定义的

#ifndef NDEBUG#define DLOG(severity) LOG(severity)#else#define DLOG(severity) true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)


调用 

LOG(INFO) << "info message";

就可以打印日志信息。


#define DLOG(severity) true ? (void) 0 : google::LogMessageVoidify() & LOG(severity)

这段定义不是很好理解,举个例子来分析。

DLOG(INFO) << "Found cookies"; 

宏展开之后就是

true ? (void) 0 : google::LogMessageVoidify() & LOG(INFO) << "Found cookies"

首先是运算符优先级的问题,加上括号之后

true ? (void) 0 : (google::LogMessageVoidify() & (LOG(INFO) << "Found cookies"))

根据Glog代码中的注释,发现google::LogMessageVoidify() 的作用是去除编译时的警告信息,忽略之。

true ? (void) 0 : (LOG(INFO) << "Found cookies")


这里有个小技巧,问号表达式中,如果条件是true,则:之后的代码并不会执行


我写了个验证逻辑

int i = 0;true ? (void) 0 : i++;assert(i == 0);


所以这样定义DLOG宏,在Release模式下

DLOG(INFO) << "Found cookies"; 

展开之后是

(void) 0;


0 0
原创粉丝点击