Caribou
Caribou

Reputation: 2081

use of std::ends() and freeze(false)

I am looking over some legacy code and there is a fair amount of stringstream usage. The code is generating messages generally from various types ok so far. Apart from the fact that it is in some cases doing the following:

   std::ostringstream f1;
   f1 << sDirectory << mFileName << sFileExtension << '\0';

and in others doing (Just illustration)

   std::ostringstream f1;
   f1 << sDirectory << mFileName << sFileExtension << std::ends;

I believe These calls are because further on it accesses f1.str().c_str() and needs to null terminate it.

Is there any difference in these calls ? I see from http://en.cppreference.com/w/cpp/io/manip/ends that std::ends doesn't flush, is std::ends different across different platforms (Linux/Windows/Mac)? Should I prefer one over the other?

Further to that I read that there should be a call to freeze(false) on the stringstream later in the scope (after str() use) to allow the buffer to be deallocated (http://en.cppreference.com/w/cpp/io/ostrstream/freeze). Again (possibly I misread or misunderstood) but there is no call to freeze(false) so does that indicate that every stream above is leaking?

N.B. FYI This is Visual Studio 2005/Windows 7 but I don't know if that has any baring.

Apologies if I'm being dense...

Upvotes: 1

Views: 128

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110748

std::ends is defined as having the following effect:

Inserts a null character into the output sequence: calls os.put(charT()).

When charT is char, it is value initialized to have the value 0, which is equivalent to the character literal \0. So when charT is char, which it usually is, the two lines of code are exactly the same.

However, using std::ends will work well even when the character type of your stream is not char.

Upvotes: 1

Related Questions