重新解释与unsigned char*和char*之间的强制转换

3 c++ templates casting

我想知道是否有必要在下面的函数中重新解释.ITER_T可能是char*,unsigned char*,std :: vector <unsigned char> iterator,或类似的东西.到目前为止它似乎没有受到伤害,但是铸造是否会影响字节的复制方式?

template<class ITER_T>
char *copy_binary(
  unsigned char length,
  const ITER_T& begin)
{
  // alloc_storage() returns a char*
  unsigned char* stg = reinterpret_cast<unsigned char*>(alloc_storage(length));
  std::copy(begin, begin + length, stg);
  return reinterpret_cast<char*>(stg);
}
Run Code Online (Sandbox Code Playgroud)

Wol*_*ngP 6

reinterpret_casts用于低级实现定义的强制转换.根据标准,reinterpret_casts可用于以下转换(C++ 03 5.2.10):

  • 指向整数类型的指针
  • 积分类型到指针
  • 指向函数的指针可以转换为指向不同类型函数的指针
  • 指向对象的指针可以转换为指向不同类型对象的指针
  • 指向成员函数的指针或指向数据成员的指针可以转换为不同类型的函数或对象.除了指针a转换回其原始类型之外,这种指针转换的结果是未指定的.
  • 如果指向类型A的指针可以使用a显式转换为类型B,则可以将类型A的表达式转换为对类型B的引用reinterpret_cast.

也就是说,reinterpret_cast在你的情况下使用它不是一个好的解决方案,因为标准没有指定转换为不同的类型,尽管从大多数机器上的char *to unsigned char *和back转换应该可以工作.

在你的情况下,我会考虑static_cast通过定义stg类型来使用或不使用char *:

template<class ITER_T>
char *copy_binary(
  unsigned char length,
  const ITER_T& begin)
{
  // alloc_storage() returns a char*
  char* stg = alloc_storage(length);
  std::copy(begin, begin + length, stg);
  return stg;
}
Run Code Online (Sandbox Code Playgroud)

  • 除了关于使用'static_cast'的部分之外,这一切都很好.我的理解是静态强制转换只能用于在相关指针类型和`void*`之间进行转换.'unsigned char'和'char'是根据标准不相关的类型,因此这种情况仅由reinterpret_cast中的第4个子弹覆盖. (2认同)