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 安全吗?


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01