stringstream temporary ostream return problem

前端 未结 2 762
别跟我提以往
别跟我提以往 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;
    }
    

提交回复
热议问题