c++ - 仅当指针作为参数传递给函数时才存在类型别名问题吗?

标签 c++ pointers language-lawyer strict-aliasing type-alias

据我所知,当两个指针(或引用)彼此不键入别名时,编译器假设它们寻址不同的位置并对其进行某些优化(例如,重新排序指令)是合法的。因此,使指向不同类型的指针具有相同的值可能会出现问题。但是,我认为这个问题仅适用于将两个指针传递给函数时。在创建两个指针的函数体内,编译器应该能够确定它们之间的关系,即它们是否寻址相同的位置。我说得对吗?

最佳答案

As far as I know, when two pointers (or references) do not type alias each other, it is legal to for the compiler to make the assumption that they address different locations and to make certain optimizations thereof, e.g., reordering instructions.

正确。例如,GCC 确实执行这种形式的优化,可以通过传递标志 -fno-strict-aliasing 来禁用它。

However, I think this issue only applies when the two pointers are passed to functions. Within the function body where the two pointers are created, the compiler should be able to make sure the relationship between them as to whether they address the same location. Am I right?

该标准不区分这些指针的来源。如果您的操作有未定义的行为,则程序也有未定义的行为。编译器没有义务在编译时分析操作数,但他可能会给你一个警告。

关于c++ - 仅当指针作为参数传递给函数时才存在类型别名问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28114585/

相关文章:

C++标准提案代码: what are N and P?

c - scanf ("%d%d", &x, &x) 是否定义明确?

c++ - c++中关于const成员函数的问题

c++ - 使用boost将gzip压缩/解压缩到内存中

C++ 强制转换运算符重载和多态性

pointers - 什么时候应该在赋值的两边使用 "&"?

C++,set_terminate 是每个线程的本地吗?

c++ - 为什么当内存足够时 malloc() 会失败?

c++ - 你怎么解释 *(y_ptr)&val;

c - 如何复制 char 指针数组的值?