How can I create my own stringbuf?

Ok, so here is what I currently have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class CStringBuffer : public std::wstringbuf
{
public:
	CStringBuffer()
		: std::wstringbuf()
	{ }
	virtual ~CStringBuffer()
	{ }

public:
	//Operators.
	operator LPWSTR()
	{
		wchar_t *ptr = this->gptr();
		return this->gptr();
	}
};


Basically, I just need a string buffer because I am working with the Windows API MultiByteToWideChar(), and I want the buffer managed. So my first thought was: Use a string stream (well, a wostringstream) and that's it. Well, it seems that I could not get access to the underlying buffer.

Reading a bit, I discovered that the string stream uses an internal string buffer, and that it seems quite possible to inherit from the default class, in this case std::wstringbuf. So good. I went ahead and created the class you see above, and then set the buffer in the string stream using set_rdbuf(). The operator found in the class provides the raw pointer and all is good: I can call MultiByteToWideChar() and I can see how the memory contents change while debugging in a memory window. Nice.

But by the time I call str() on the string stream I get a blank string. Why?

I also accept easier ways of getting the job done, which is: Convert a multi byte string encoded using the default Windows encoding to Unicode.
Ok, so debugging the STL code I found out that even though the code below does use the passed string buffer object (via set_rdbuf()), the call to str() in the string stream uses a different, standard string buffer object.

1
2
3
4
5
6
std::wostringstream sBuff;
CStringBuffer buff;
sBuff.set_rdbuf(&buff);
sBuff << std::setw(wideSize) << L"";  //This produces a string allocated inside the buff object as expected.
...
sbuff.str();  //This queries another string buffer object allocated since the beginning inside the string stream. 


So at this point I am thinking: There is a design flaw in this implementation of the STL. Am I correct? This is the STL provided with Visual Studio Ultimate 2010, SP1.
I ended up posting this as a bug in MS Connect: https://connect.microsoft.com/VisualStudio/feedback/details/698682/stl-string-streams-dont-always-use-the-assigned-stringbuf-object-via-set-rdbuf

If you feel this is a bug too, please visit the link and vote it up.
Topic archived. No new replies allowed.