Is it fail-safe to use CString as parameter type for the method CStringT::Format?

BlueTune 21 Reputation points
2020-11-26T06:25:58.497+00:00

I am using the following method: CStringT::Format.

Is it fail-safe to use CString as parameter type, just like in the following?

CString a = _T("This is a %s. And it %s.");  
CString b = _T("test");  
CString c = _T("works");  
  
CString str;  
str.Format(a, b, c);  
  
// str == "This is a test. And it works."  

If it is fail-safe, please also provide a reason for this fact.

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,877 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jeanine Zhang-MSFT 11,106 Reputation points Microsoft External Staff
    2020-11-26T08:38:33.007+00:00

    Hi,

    According to the Doc:

    You can freely substitute CStringT objects for PCXSTR function arguments.

    Whenever a function parameter expects a constant C-style string, you can pass a CStringT object, that is implicitly converted by invoking the operator PCXSTR().

    For more details I suggest you could refer to the link: https://stackoverflow.com/questions/48245284/using-cstring-object-in-cstringformat

    Best Regards,

    Jeanine


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Viorel 120.4K Reputation points
    2020-11-26T08:58:12.073+00:00

    Even if sizeof(CString) is the size of a pointer, and the only member of CString is a pointer to zero-terminated string or null, the documentation recommends: “[…] it is essential that you use an explicit type cast when passing a CString object to a function that takes a variable number of arguments”. See: https://learn.microsoft.com/en-us/cpp/atl-mfc-shared/cstring-operations-relating-to-c-style-strings?view=msvc-160#_core_using_cstring_objects_with_variable_argument_functions.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.