我最近了解到C++标准包含“严格别名规则”,禁止通过不同类型的变量引用相同的内存位置。
但是,该标准允许char
类型合法地别名任何其他类型。这是否意味着reinterpret_cast
只能合法地用于将类型转换为char *
或char &
?
我认为严格别名允许在继承层次结构中的类型之间进行转换,但我认为这些情况通常会使用dynamic_cast<>?
谢谢
我最近了解到C++标准包含“严格别名规则”,禁止通过不同类型的变量引用相同的内存位置。
但是,该标准允许char
类型合法地别名任何其他类型。这是否意味着reinterpret_cast
只能合法地用于将类型转换为char *
或char &
?
我认为严格别名允许在继承层次结构中的类型之间进行转换,但我认为这些情况通常会使用dynamic_cast<>?
谢谢
reinterpret_cast
。在cppreference页面上列出了11种不同的情况。T *
转换为U *
,以及将T
转换为U &
。U
有几种合法类型。同样的cppreference页面提供了一个情况列表;您可以在C++标准草案中阅读规则的确切文本。还有其他有用的reinterpret_cast
用法。
是的,有时候想要将指针的值存储在整数类型中。
使用C++风格的转换唯一的方法是使用reinterpret_cast
。
例如:
auto pointerValue = reinterpret_cast<std::uintptr_t>(pointer);
有时,您想要将数据存储在堆栈上,但稍后初始化。使用动态分配和指针不能使用堆栈。std::aligned_storage
作为原始的对齐内存块非常出色。
struct MyStruct {
int n;
std::string s;
};
// allocated on automatic storage
std::aligned_storage<sizeof(MyStruct), alignof(MyStruct)>::type storage;
// actually initialize the object
new (&storage) MyStruct;
// using the object
reinterpret_cast<MyStruct*>(&storage)->n = 42;
我相信还有很多其他用途我不知道,但这些是我已经使用过的。
auto *p = reinterpret_cast<MyStruct *>(&storage); new(&storage) MyStruct; p->n = 42;
。 - M.Mauto* p = new(&storage) MyStruct;
来避免强制转换。 - T.C.char* ptr = /* ... */
uintptr_t ptrInt = reinterpret_cast<uintptr_t>(ptr);
你获得的特定整数值在不同平台上可能不具备可移植性,但这是一种安全且定义清晰的操作。