Why does < instead of << in stream output still compile?

后端 未结 2 1314
北恋
北恋 2021-01-11 14:34

Today I made a small typo in my program, and was wandering why I wasn\'t getting any output, although the program compiled fine. Basically it reduces to this:



        
相关标签:
2条回答
  • 2021-01-11 15:17

    Yes, the compiler is converting cout to a void*. If you use the -S switch to get the code's disassembly, you'll see something like this:

        mov edi, OFFSET FLAT:std::cout+8
        call    std::basic_ios<char, std::char_traits<char> >::operator void*() const
        cmp rax, OFFSET FLAT:.LC0
        setb    al
        test    al, al
    

    Which makes it clear that operator void* is the culprit.

    Contrary to what Bill Lynch said, I'm able to reproduce it with —std=c++11 on Compiler Explorer. However, it does appear to be an implementation defect, since C++11 should have replaced operator void* with operator bool on basic_ios.

    0 讨论(0)
  • 2021-01-11 15:30

    This is only valid before C++11.

    You're basically doing: ((void *) std::cout) < ((char *) "test")

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