I am looking through some legacy code and found that temporary std::string objects are being used liberally throughout the code to convert const char* to force the use of :
inline std::ostream & operator << (std::ostream & s, const std::string & str)
within which str.c_str() is used to effect the call to
template<class _Traits> inline
basic_ostream<char, _Traits>& __CLRCALL_OR_CDECL operator<<(
basic_ostream<char, _Traits>& _Ostr,
const char *_Val)
Weirdly I think this was done because someone created a const char* insertion operator which recursed... Anyway The reason was lost in the dim distant past... I removed it when I noticed exactly what was happening and it all works (AFAIK).
While experimenting with this issue, I redefined operator<<(std::ostream& , const char*) to do the following.
//
// Disclaimer - experiment!!! not enshrined in code.
//
inline std::ostream & operator << (std::ostream & s, const char * str)
{
//formerly return s << std::string(str);
if( str ) s.rdbuf()->sputn( str , strlen(str) );
return s;
}
Question
apart from the strlen call (preempting some comments) is there much of a downside to bypassing the insertion operator? (I saw some try catch logic in the operator I'm bypassing and I could place this into the operator above perhaps.)
Stream inserters do formatted input, controlled by a double handful of flags in the stream object. Stuffing characters directly into the output buffer bypasses this formatting, so manipulators like setw won't affect the output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With