Search code examples
visual-c++c-stringscode-analysis

C26492 Don't use `const_cast` to cast away const or volatile (type.3)


Here is an interesting discussion about not using const_cast where you are encouraged to use mutable.

Here is my code:

MENUITEMINFO sInfo{};
sInfo.cbSize = sizeof(MENUITEMINFO);
sInfo.fMask = MIIM_STRING;
sInfo.dwTypeData = const_cast<TCHAR*>(strHostLabel.GetString());
SetMenuItemInfo(pMnuSwap->GetSafeHmenu(), SwapAssignment::Host, TRUE, &sInfo);
sInfo.dwTypeData = const_cast<TCHAR*>(strCoHostLabel.GetString());
SetMenuItemInfo(pMnuSwap->GetSafeHmenu(), SwapAssignment::Cohost, TRUE, &sInfo);

The code analysis is telling me:

warning C26492: Don't use const_cast to cast away const or volatile (type.3).

I understand that they are saying it is bad design to do this and that you can adjust a class to allow it to still be const but permit certain variables to be modifiable. Atleast, I understood that from the linked discussion.

But that does not apply in this context.


I saw the answers for this question (How to convert LPCWSTR to LPWSTR) which implies copying the string to another one. Is there no simpler way?

  • sInfo.dwTypeData is of type LPWSTR.
  • GetString returns a LPCWSTR.

This was why I used const_cast. Is there another way to make this code analysis compatible without overcomplicating it?

My code compiles for both 32 bit and 64 bit. This is why I have historically used TCHAR.


Solution

  • The cleanest way, I believe, would be to use GetBuffer.

    At some point you will find a function that really needs non-const string :)