Search code examples
c++const-cast

C++ const cast, unsure if this is secure


It maybe seems to be a silly question but i really need to clarify this:

Will this bring any danger to my program?

Is the const_cast even needed?

If i change the input pointers values in place will it work safely with std::string or will it create undefined behaviour?

So far the only concern is that this could affect the string "some_text" whenever I modify the input pointer and makes it unusable.

std::string some_text = "Text with some input";

char * input = const_cast<char*>(some_text.c_str());

Thanks for giving me some hints, i would like to avoid the shoot in my own foot


Solution

  • As an example of evil behavior: the interaction with gcc's Copy On Write implementation.

    #include <string>
    #include <iostream>
    
    int main() {
        std::string const original = "Hello, World!";
        std::string copy = original;
    
        char* c = const_cast<char*>(copy.c_str());
        c[0] = 'J';
    
        std::cout << original << "\n";
    }
    

    In action at ideone.

    Jello, World!

    The issue ? As the name implies, gcc's implementation of std::string uses a ref-counted shared buffer under the cover. When a string is modified, the implementation will neatly check if the buffer is shared at the moment, and if it is, copy it before modifying it, ensuring that other strings sharing this buffer are not affected by the new write (thus the name, copy on write).

    Now, with your evil program, you access the shared buffer via a const-method (promising not to modify anything), but you do modify it!

    Note that with MSVC's implementation, which does not use Copy On Write, the behavior would be different ("Hello, World!" would be correctly printed).

    This is exactly the essence of Undefined Behavior.