views:

256

answers:

2

From http://stackoverflow.com/questions/559483/cstring-to-char, ReleaseBuffer() must be used after GetBuffer(). But why? What will happen if I don't use ReleaseBuffer after GetBuffer()? Can somebody show me an example? Thanks.

+2  A: 

I'm not sure that this will cause a memory leak, but you must call ReleaseBuffer to ensure that the private members of CString are updated. For example, ReleaseBuffer will update the length field of the CString by looking for the terminating null character.

Nick Meyer
@Nick, thank you. I just wrote a small program to test ReleaseBuffer(), you are right!! Thank you!
Landy
+3  A: 

What will happen if I don't use ReleaseBuffer after GetBuffer()?

I haven't used MFC (and hopefully won't ever have to touch it with a ten-foot pole) but, as a rule of thumb, whenever you have an API that has both GetXXX() and ReleaseXXX() (especially when the result of GetXXX() conveniently is of the type that ReleaseXXX() takes) -- then when you forget to call ReleaseXXX() for every one of your GetXXX() calls, you will leak an XXX.

sbi
@sbi, thank you. From this post - http://stackoverflow.com/questions/559483/cstring-to-char, "calling the GetBuffer method won't lead to any memory leaks. Because the destructor is going to deallocate the buffer anyway. "
Landy
+1 for a fabulous rule of thumb.
Binary Worrier
@Landy: Well, there you go. So, in this case, the rule of thumb seems to fail. I guess that's why it is called a "rule of thumb", after all, no? Well, did I say I dislike MFC? Now there's one more reason to do so. An API where `GetXXX()` and `ReleaseXXX()` don't come in pairs just plain sucks... Anyway, from http://msdn.microsoft.com/en-us/library/awkwbzyc.aspx: "After you modify the contents of a CString object directly, you must call ReleaseBuffer before you call any other CString member functions."
sbi
@sbi: Thank you. MSDN says "After you modify the contents of a CString object directly, you must call ReleaseBuffer before you call any other CString member functions." But MSDN doesn't say why I *must* call ReleaseBuffer. In Nick's post, he said ReleaseBuffer() will update the length field of CString. It's a good reason I think. Thank you.
Landy