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;开发者_如何学JAVA
crashes by stackoverflow as predicted by Visual ?
Btw, replacing m.text
by m.text.c_str()
works.
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.
Only thing I can think of is that it doesn't have an operator<< for std::string so it looks for a conversion and finds the one argument constructor TextMessage(std::string).
It is often advisable to prevent unexpected calls to one argument constructors by making them explicit.
explicit TextMessage(std::string _text):text(_text){}
Then it will not consider the constructor for implicit conversions.
Its because m.text
is std::string
and it gets converted inside the operator to TextMessage
and the operator is called again.
精彩评论