我通常在 C/C++ 代码中使用 C 类型转换。我的问题是,在转换类型中添加“const”关键字对结果有什么意义吗?
例如,我可以想出几个场景:
const my_struct *func1()
{
my_struct *my_ptr = new my_struct;
// modify member variables
return (const my_struct *)my_ptr;
// return my_instance;
}
在这一个中,该函数构造了一个结构的新实例,并将其转换为一个常量指针,因此调用者将无法进一步修改其内部状态,除非将其删除。是否需要、推荐或根本不需要“const”强制转换,因为任一 return 语句都有效。
在这一个中, my_base
是 my_derive
的基类。
const my_base *func2(const my_derive *my_ptr)
{
return (const my_base *)my_ptr;
// return (my_base *)my_ptr;
}
由于 my_ptr
已经是一个 const 指针,使用 (my_base *)
进行强制转换会涉及用于删除 const 的 const_cast 和返回时另一个隐式 const_cast 吗?
是否有任何理由将“const”添加到整数函数参数,因为更改它永远不会影响函数外部的状态?
void func3(const int i)
{
// i = 0; is not allowed, but why, as it is harmless?
}
在转换整数时添加“const”怎么样?我认为这应该类似于 func2()
。
void func4(short i)
{
const unsigned int j = (const unsigned int) i;
// const unsigned int j = (unsigned int) i;
}
如我错了请纠正我。考虑到类型转换可能是一个常见问题解答,我不确定这是否与其他任何内容重复。谢谢!
原文由 Crend King 发布,翻译遵循 CC BY-SA 4.0 许可协议
在转换类型中添加
const
关键字意味着结果将是恒定的。以下将不会在 C++ 中编译(在 C 中无效):你真的不应该在你的 C++ 代码中使用 C 类型转换。它不安全,仅应用于与遗留 C 代码兼容。您应该改用 C++ 强制转换。
在
func3
通常情况下const
不使用限定符。如果函数参数没有指针或引用类型,则没有很大的理由将const
限定符添加到函数参数中。考虑以下:当您将左值分配给右值时,如
func4
,无需在强制转换表达式中显式指定const
限定符。左值到右值的转换将根据 C++ 标准 4.1 隐式执行。