c++ - C++ 中的部分 const 类型转换

标签 c++ struct casting constants partial

有时,在传递或返回结构时,可能需要将某些字段设为常量:

struct A
{
   char c;
   int x;
};

struct B
{
   const char c;
   int x;
};

void process(B& b)
{
   if(b.c=='1')
      b.x++;
}

void test()
{
   A a;
   a.c = '1';
   a.x = 0;
   process(reinterpret_cast<B&>(a));
}

这种部分 const 类型转换是否足够便携和安全?

最佳答案

没有这样的技术是不安全的,它是未定义的行为 - 在不相关的类型之间进行转换,即使它们看起来相似,也绝不安全。

关于c++ - C++ 中的部分 const 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27962260/

相关文章:

c++ - 正则表达式回溯导致堆栈溢出

c++ - 将参数隐式转换为 bool

c++赋值删除分配值的来源

c++ - 缓冲区到结构的转换

xml - 戈朗 : Undefined field in struct error

c++ - 数据文件输入/输出错误

c++ - 如何通过转换类型指针将 char 数组转换为 uint16_t?

java - 如何避免在 Java 泛型扩展 Comparable 接口(interface)中进行未经检查的强制转换?

C++最优化转换

c++ - find() 返回 unsigned int 的最大值