Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator<< stackoverflow

Consider the following code :

class TextMessage{
public :
    TextMessage(){};
    TextMessage(std::string _text):text(_text){}
    std::string text;
    friend std::ostream & operator<<( std::ostream & os, const TextMessage & m);
};
std::ostream & operator<<( std::ostream & os, const TextMessage & m){
    return os << "text message : " << m.text;
}

Why on earth :

  • does Visual 2010 issue a C4717 warning in operator <<
  • does std::cout << textMsgInstance; crashes by stackoverflow as predicted by Visual ?

Btw, replacing m.text by m.text.c_str() works.

like image 890
Calvin1602 Avatar asked Jun 01 '11 15:06

Calvin1602


1 Answers

I'm guessing that you failed to #include <string>. Thus, when the compiler comes to output a std::string, it can't, and starts looking for implicit conversions- and your implicit constructor to a TextMessage looks like just the bill. But wait- now we're outputting a TextMessage in the TextMessage's output function, and bam.

like image 94
Puppy Avatar answered Oct 09 '22 11:10

Puppy