Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this defined?

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?

like image 464
DarthRubik Avatar asked Jun 30 '16 01:06

DarthRubik


People also ask

Is this is it meaning?

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.

What do you mean by defined?

adjective. determined, fixed, or clearly marked out as to extent, outline, or form: an itchy red rash with sharply defined edges.

What kind of word is this?

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.


1 Answers

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 ints, 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 */ }
}
like image 197
Dan R Avatar answered Sep 30 '22 22:09

Dan R