Is it determined?

Suppose I have the following class:

struct A{ void method(A& otherA) const{ /* Mutate otherA */ } }; 

And then I have the following:

 A myA; myA.method(myA); 

I told the compiler that method will not change the this instance, but does the compiler understand that I can pass this instance as a parameter?

Can I break the material by doing this? Is this a specific behavior?

+6
source share
1 answer

This is completely normal and this is not a problem. What you do in this example is sometimes called "aliasing" - when two arguments actually refer to the same object.

Consider an even simpler case in simple C:

 void foo(int* a, const int* b) { *a += *b; } 

This function takes two pointers to int s and adds the second to the first. And of course, this code is absolutely right for using my foo function.

 int x = 10; foo(&x, &x); // now x is 20 

If you do not like this behavior in this case, it is best to add validation to your method, for example

 void A::method(A& otherA) const { if (this == &otherA) { /* aliasing detected */ } else { /* proceed as normal */ } } 
+10
source

All Articles