visual-c++mfcc-strings

Is there a worked example of using CStrBufT with a CString?


I stumbled on this class when browsing the internet this morning: CStrBufT.

I understand that it is meant to be used instead of:

CString::GetBuffer
CString::GetBufferSetLength
CString::ReleaseBuffer

But the documentation lacks a usage example, and my searches on the internet don't seem to show this class being used, but the respective CString methods.

What is the correct way to use this wrapper when you need a buffer?


Solution

  • Most commonly, you use CStrBuf when you have to pass a string buffer to a C API that is filled by the called function. Here is an example that calls GetModuleFileName() from C++ (off the top of my head).

    // assume we got a valid HMODULE somewhere
    HMODULE module = ...;
    
    // somehow decide on a buffer size; for simplicity, use a constant here
    DWORD size = MAX_PATH;
    
    CString filename;
    GetModuleFileName(module, CStrBuf(filename, size), size);
    
    // the result is now in filename
    
    // (note: error checks omitted for brevity)
    

    CStrBuf has an operator LPTSTR, i.e., it can be converted to a writable string implicitly. For this reason, it can be written as a temporary object in place of an LPTSTR argument (the second argument in this example).

    Note that CStrBufT is a class template just like CStringT is. Stick with the specialization CStrBuf that is akin to CString.