简体   繁体   中英

How do I perform const_cast in this case correctly?

I have a function

static bool Validate(const char& letter, string& aWord)

I need to invoke it

Validate(letter, aWord); // where aWord is const

What is the correct way to const_cast in this case?

If you are absolutely sure that the function does not modify the string, you can do this:

Validate (letter, const_cast<std::string &>(aWord));

However, a safer thing to do, albeit it an unnecessary copy if the signature could hypothetically be changed to const , would be to copy the string and pass the copy.

std::string copyOfAWord = aWord;
Validate (letter, copyOfAWord);

If it does change something, your copy would have the results instead, but it would break your logic in the first place.

The correct way is NOT to cast it.

The signature here

static bool Validate(const char& letter, string& aWord)

is saying that Validate() may alter the parameter aWord . Thus passing it a const value that is going to be mutated is undefined behavior (if it is mutated (see last paragraph)).

If you are sure that Validate() does not mutate aWord then Still Dont cast away constness. In this case change its signature to reflect the guarantees provided.

The fact that aWord is not const means the it could mutate aWord . Even if it does not mutate in this version, somebody in the future may come along and change that. Then your program will break in such a horrible way that it will be imposable to find the error.

If you are casting away constness then you are doing something wrong.

The only solution (if you can;t change the interface) here is to pass a non cost version. Since you don;t have one you should create one:

std::string    aWordTmpCopy(aWord);
Validate(letter, aWordTmpCopy);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM