首页 > 解决方案 > When to assume aliasing

问题描述

I am brushing up my knowledge on strict aliasing and I came across this famous article: What is the Strict Aliasing Rule and Why do we care?

signed int foo( const signed int &si1, int &si2); // Hard to show this one assumes aliasing

But I have problems understanding the statement: "Hard to show this one assumes aliasing". What does that mean in this context? I feel like this statements wants to point out that si1 and si2 might (or might not) refer to the same object? But I am not sure.

标签: c++alias

解决方案


See the example above, which is about

signed int foo( signed int &si, unsigned int &ui ) { 

and where it is explained that you can see from the compilers output that the optimizer does assume that there is aliasing.

All the examples in the list are cases where the compiler has to "assume aliasing" because the items are the ones where aliasing is allowed. In "// Hard to show this one assumes aliasing" the author just states that from the compilers output it isn't as easy to see that this is the case as compared to the example before.

I feel like this statements wants to point out that si1 and si2 might (or might not) refer to the same object?

Thats the case for all the items in the list. Its a list of special cases, where variables of different type are allowed to refer to the same object. The statement is about how you can see the effect of the rule in the compilers output.

In different words: In general asliasing is not allowed. Hence the compiler can safely assume pointers or references of different type do not refer to the same object. Thats what the optimizer does all the time: It assumes you wrote code that is in accordance with the rules. Then it applies transformations to the code that will result in something that has exactly same observable behaviour. This all works under the assumption that you wrote valid code. Here in this siutation the compiler has to be a bit more cautious, because the listed exceptions give more freedom to you, and less freedom to the optimizer. It now cannot assume that two references of different type never refer to the same object, but instead it has to "assume that there is aliasing" (which slighltly limits possibilities for optimization).


推荐阅读