Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

#include <iostream>

int main()
{
    std::cout < "test"; // no << but <
}

I have absolutely no idea what kind of implicit conversion is performed here so the program still compiles (both g++4.9.2 and even g++5). I just realized that clang++ rejects the code. Is there a conversion to void* being performed (cannot think of anything else)? I remember seeing something like this, but I thought it was addressed in g++5, but this doesn't seem to be the case.

EDIT: I was not compiling with -std=c++11, so the code was valid in pre-C++11 (due to conversion to void* of ostream). When compiling with -std=c++11 g++5 rejects the code, g++4.9 still accepts it.

like image 830
vsoftco Avatar asked Apr 18 '15 22:04

vsoftco


1 Answers

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.

like image 184
zneak Avatar answered Nov 15 '22 12:11

zneak