什么时候和如何转换为char指针允许? [英] When and how is conversion to char pointer allowed?

查看:176
本文介绍了什么时候和如何转换为char指针允许?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以通过转换 T * 来表示 T 对象转换为 char * 。至少在实践中:

We can look at the representation of an object of type T by converting a T* that points at that object into a char*. At least in practice:

int x = 511;
unsigned char* cp = (unsigned char*)&x;
std::cout << std::hex << std::setfill('0');
for (int i = 0; i < sizeof(int); i++) {
  std::cout << std::setw(2) << (int)cp[i] << ' ';
}

这将输出 511 在我的系统上: ff 01 00 00

This outputs the representation of 511 on my system: ff 01 00 00.

这里。哪些转换允许我将 int * 转换为 unsigned char * 以及转换所需的转换?一旦我施放,我会调用未定义的行为吗?我可以施放任何 T * 类型吗?

There is (surely) some implementation defined behaviour occurring here. Which of the casts is allowing me to convert an int* to an unsigned char* and which conversions does that cast entail? Am I invoking undefined behaviour as soon as I cast? Can I cast any T* type like this? What can I rely on when doing this?

推荐答案


哪些演员允许我转换 int 到 unsigned char *

在这种情况下,C风格的转换与 reinterpret_cast< unsigned char *> 相同。

That C-style cast in this case is the same as reinterpret_cast<unsigned char*>.


我可以这样投放任何T *类型吗?

Can I cast any T* type like this?

yes部分:您可以安全地将任何指针类型转换为 char * unsigned char * code> const 和/或 volatile 限定符)。

Yes and no. The yes part: You can safely cast any pointer type to a char* or unsigned char* (with the appropriate const and/or volatile qualifiers). The result is implementation-defined, but it is legal.

没有部分:标准显式地允许 char * unsigned char * 作为目标类型。但是,您不能(例如)将 double * 安全地转换为 int * 。这样做,你已经跨越从实现定义的行为边界到未定义的行为。它违反了严格的别名规则。

The no part: The standard explicitly allows char* and unsigned char* as the target type. However, you cannot (for example) safely cast a double* to an int*. Do this and you've crossed the boundary from implementation-defined behavior to undefined behavior. It violates the strict aliasing rule.

这篇关于什么时候和如何转换为char指针允许?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆