Is const_cast safe?(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
这篇关于const_cast 安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:const_cast 安全吗?
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
