0

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.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
  • 1
    Copying the string can be pretty simple. `stdTstring hostLabel = strHostLabel.GetString(); sInfo.dwTypeData = &hostLabel[0];` Assuming that you have a typedef named `stdTstring` (or pick your own name). – Ben Voigt Oct 19 '21 at 18:37
  • 1
    Since the structure is being passed to `SetMenuItemInfo`, the pointer will be used only to read the string, so the cast is safe. The compiler doesn't know this, though. (If you had passed it to `GetMenuItemInfo`, then it would be a different story.) – Raymond Chen Oct 19 '21 at 19:09
  • @RaymondChen So I should use `prama` to suppress. – Andrew Truckle Oct 19 '21 at 19:10

1 Answers1

1

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

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

Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27