Is const_cast safe?

后端 未结 6 2090
名媛妹妹
名媛妹妹 2020-11-22 12:17

I can\'t find much information on const_cast. The only info I could find (on Stack Overflow) is:

The const_cast<>() i

6条回答
  •  囚心锁ツ
    2020-11-22 12:54

    const_cast is safe only if you're casting a variable that was originally non-const. For example, if you have a function that takes a parameter of a const char *, and you pass in a modifiable char *, it's safe to const_cast that parameter back to a char * and modify it. However, if the original variable was in fact const, then using const_cast will result in undefined behavior.

    void func(const char *param, size_t sz, bool modify)
    {
        if(modify)
            strncpy(const_cast(param), sz, "new string");
        printf("param: %s\n", param);
    }
    
    ...
    
    char buffer[16];
    const char *unmodifiable = "string constant";
    func(buffer, sizeof(buffer), true);  // OK
    func(unmodifiable, strlen(unmodifiable), false); // OK
    func(unmodifiable, strlen(unmodifiable), true);  // UNDEFINED BEHAVIOR
    

提交回复
热议问题