3

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.)

Caribou
  • 2,070
  • 13
  • 29
  • This functionality already exists (http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2). I fail to see the motivation behind this question. – R. Martinho Fernandes Nov 12 '12 at 15:00
  • @R.MartinhoFernandes I was curious really - I use insertion operators all the time - the operators add a level of indirection and I hadn't considered doing it this way for exactly that reason. – Caribou Nov 12 '12 at 15:03

1 Answers1

1

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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • Ok, right - I see what you mean. This stuff is basically dumping unformatted text so I didn't think along those lines. - thx – Caribou Nov 12 '12 at 15:21