In this Stack Overflow answer it is demonstrated that aliasing in C++ can slow down your code. And aliasing in C++ doesn't only apply to pointers, it applies also to references, and more generally to these types specified by the standard. Particularly, there is
an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union)
So according to my understanding, if I have code like below,
class A{
public:
int val;
};
void foo(vector<A> & array, int & size, A & a0) {
for(int i=0;i<size;++i) {
array[i].val = 2*a0.val;
}
}
and it is possible that a0
can alias one of the elements in array
, also possibly alias size
because of the aforementioned quote, so a0
and size
have to be loaded for each iteration resulting in a performance drop.
- Then my question is what should I do to the code to avoid the aliasing, and improve the performance?
- Passing by
const &
won't help since it won't avoid aliasing as specified by the standard. Passa0
by value? But this will make a copying ofa0
which I don't like, since in practice, classA
may be very complex and copying is a very expensive option. - Is there a general solution to avoid aliasing in C++? If yes, what is it?