Suppose I have the following class:
struct A{
void method(A& otherA) const{
/* Mutate otherA */
}
};
And then later I have this:
A myA;
myA.method(myA);
I have told the compiler that method
will not change the this
instance, but does the compiler realize that I could pass in the this
instance as a parameter?
Could I be breaking stuff by doing this? Is this defined behavior?
Definition of this is it —used to say that a very important thing is about to be done, a very important event is about to happen, etc. This is it, men. Let's take home the championship! As the car skidded out of control, I thought, "This is it.
adjective. determined, fixed, or clearly marked out as to extent, outline, or form: an itchy red rash with sharply defined edges.
The words this, that, these, and those are demonstrative pronouns. The demonstrative pronouns are used instead of a noun phrase to indicate distance in time or space in relation to the speaker. They also indicate grammatical number – singular or plural.
This is totally fine, and not a problem. What you're doing in this example is sometimes called "aliasing" - when two arguments actually refer to the same object.
Consider the even simpler case in plain C:
void foo(int* a, const int* b) { *a += *b; }
That function takes two pointers to int
s, and adds the second one to the first one. And of course this code to use my foo
function is perfectly valid:
int x = 10;
foo(&x, &x); // now x is 20
If you don't like that behavior in this case, the best thing to do would be probably to add a check within your method like
void A::method(A& otherA) const {
if (this == &otherA) { /* aliasing detected */ }
else { /* proceed as normal */ }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With