CString 到 char*

2021-12-31 00:00:00 memory-leaks c++ mfc cstring

我们在大部分代码中都使用 CString 类.但是有时我们需要转换为 char *.目前我们一直在使用 variable.GetBuffer(0) 来做这件事,这似乎有效(这主要发生在将 Csting 传递到函数需要 char * 的函数时).该函数接受这一点,我们继续前进.

然而,我们最近开始担心这是如何运作的,以及是否有更好的方法来做到这一点.

我理解它的工作方式是将一个字符指针传递给指向 CString 中第一个字符的函数,并且一切正常.

我想我们只是担心内存泄漏或任何不可预见的情况,这可能不是一个好主意.

解决方案

如果你的函数只需要读取字符串而不需要修改它,请将它们更改为接受 const char * 而不是 char*.CString 将自动为您转换,这是大多数 MFC 函数的工作方式,而且非常方便.(实际上 MFC 使用 LPCTSTR,它是 const TCHAR * 的同义词 - 适用于 MBC 和 Unicode 构建).

如果您需要修改字符串,GetBuffer(0) 非常危险 - 它不一定会为结果字符串分配足够的内存,并且您可能会遇到一些缓冲区溢出错误.>

正如其他人提到的,您需要在 GetBuffer 之后使用 ReleaseBuffer.您无需为转换为 const char * 执行此操作.

We are using the CString class throughout most of our code. However sometimes we need to convert to a char *. at the moment we have been doing this using variable.GetBuffer(0) and this seems to work ( this mainly happens when passing the Csting into a function where the function requires a char *). The function accepts this and we keep going.

However we have lately become worried about how this works, and whether there is a better way to do it.

The way i understand it to work is it passes a char pointer into the function that points at the first character in the CString and all works well.

I Guess we are just worried about memory leaks or any unforseen circumstances where this might not be a good idea.

解决方案

If your functions only require reading the string and not modifying it, change them to accept const char * instead of char *. The CString will automatically convert for you, this is how most of the MFC functions work and it's really handy. (Actually MFC uses LPCTSTR, which is a synonym for const TCHAR * - works for both MBC and Unicode builds).

If you need to modify the string, GetBuffer(0) is very dangerous - it won't necessarily allocate enough memory for the resulting string, and you could get some buffer overrun errors.

As has been mentioned by others, you need to use ReleaseBuffer after GetBuffer. You don't need to do that for the conversion to const char *.

相关文章