const_cast 安全吗?

2021-12-31 00:00:00 casting c++ const-cast

我找不到关于 const_cast 的太多信息.我能找到的唯一信息(在 Stack Overflow 上)是:

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

const_cast<>() 用于添加/删除变量的 const(ness)(或 volatile-ness).

The const_cast<>() is used to add/remove const(ness) (or volatile-ness) of a variable.

这让我很紧张.使用 const_cast 会导致意外行为吗?如果是,那是什么?

This makes me nervous. Could using a const_cast cause unexpected behavior? If so, what?

或者,什么时候可以使用 const_cast?

Alternatively, when is it okay to use const_cast?

推荐答案

const_cast 仅在您强制转换最初非const 的变量时才是安全的.例如,如果你有一个函数接受一个 const char * 的参数,并且你传入了一个可修改的 char *,那么 const_cast 是安全的code> 将该参数恢复为 char * 并修改它.但是,如果原始变量实际上是 const,那么使用 const_cast 将导致未定义的行为.

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<char *>(param), sz, "new string");
    printf("param: %s
", 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

相关文章