stringstream temporary ostream return problem

前端 未结 2 735
别跟我提以往
别跟我提以往 2020-12-30 14:28

I\'m creating a logger with the following sections:

// #define LOG(x) // for release mode
#define LOG(x) log(x)

log(const string& str);
log(const ostrea         


        
相关标签:
2条回答
  • 2020-12-30 14:49

    I think I see what's happening. This produces the expected output:

    log(std::stringstream() << 1 << "hello");
    

    while this does not:

    log(std::stringstream() << "hello" << 1);
    

    (it writes a hex number, followed by the "1" digit)

    A few elements for the explanation:

    • An rvalue cannot be bound to a non-const reference
    • It is OK to invoke member functions on a temporary
    • std::ostream has a member operator<<(void*)
    • std::ostream has a member operator<<(int)
    • For char* the operator is not a member, it is operator<<(std::ostream&, const char*)

    In the code above, std::stringstream() creates a temporary (an rvalue). Its lifetime is not problematic, as it must last for the whole full expression it is declared into (i.e, until the call to log() returns).

    In the first example, everything works ok because the member operator<<(int) is first called, and then the reference returned can be passed to operator<<(ostream&, const char*)

    In the second example, operator<<(cannot be called with "std::stringstream()" as a 1st argument, as this would require it to be bound to a non-const reference. However, the member operator<<(void*) is ok, as it is a member.

    By the way: Why not define the log() function as:

    void log(const std::ostream& os)
    {
        std::cout << os.rdbuf() << std::endl;
    }
    
    0 讨论(0)
  • 2020-12-30 14:53

    Alter your LOG() macro to this:

    #define LOG(x) do { std::stringstream s; s << x; log(s.str()); } while(0)
    

    That will let you use the following syntax in your debugging logs, so you don't have to manually construct the string stream.

    LOG("Testing" << 1 << "two" << 3);
    

    Then define it to nothing for release, and you'll have no extra allocations.

    0 讨论(0)
提交回复
热议问题