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
2010-02-26 15:18:52
@Nick, thank you. I just wrote a small program to test ReleaseBuffer(), you are right!! Thank you!
Landy
2010-02-26 16:21:17
+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
2010-02-26 15:32:14
@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
2010-02-26 15:59:22
@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
2010-02-26 16:16:10
@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
2010-02-26 16:31:25