Standard no-op output stream

后端 未结 6 1813
余生分开走
余生分开走 2020-11-29 03:25

Is there a way to create an ostream instance which basically doesn\'t do anything ?

For example :

std::ostream dummyStream(...);
dummyStream <<         


        
6条回答
  •  离开以前
    2020-11-29 03:52

    If you are concerned about the overhead of your debugger then you can write a very simple code to void out your debug messages on compilation. This is what I use for my c++ programs.

    #include 
    #define DEBUGGING // Define this in your config.h or not.
    #ifdef DEBUGGING
    /*
     * replace std::cout with your stream , you don't need to
     * worry about the context since macros are simply search
     * and replace on compilation.
     */
    #define LOG_START std::cout <<
    #define LOG_REDIR <<
    #define LOG_END   << std::endl;
    #else
    #define LOG_START (void)
    #define LOG_REDIR ;(void)
    #define LOG_END   ;
    #endif // DEBUGGING
    
    int main(){
    LOG_START "This is a log message " LOG_REDIR "Still a log message." LOG_END;
    return 0;
    }
    

    Now when making your project , check if the user wants to disable the logging , if so , just undefine the DEBUGGING macro or whatever macro you choose to check for.

    Now your code will be optimized by the compiler , Because when anything is voided , it will not be included in the resulting binary(most of the time) , making the binary production ready.

提交回复
热议问题