这个定义了吗?

Dar*_*bik 6 c++ const language-lawyer

假设我有以下课程:

struct A{
  void method(A& otherA) const{
    /* Mutate otherA */
  }
};
Run Code Online (Sandbox Code Playgroud)

然后我有这个:

A myA;
myA.method(myA);
Run Code Online (Sandbox Code Playgroud)

我告诉编译器method不会更改this实例,但编译器是否意识到我可以将this实例作为参数传递?

这样做我可以打破这些东西吗?这是定义的行为吗?

Dan*_*n R 10

这完全没问题,也不是问题.你在这个例子中所做的有时被称为"别名" - 当两个参数实际上引用同一个对象时.

考虑简单C中更简单的情况:

void foo(int* a, const int* b) { *a += *b; }
Run Code Online (Sandbox Code Playgroud)

该函数需要两个指向ints的指针,并将第二个指针添加到第一个指针.当然,使用我的foo函数的代码是完全有效的:

int x = 10;
foo(&x, &x); // now x is 20
Run Code Online (Sandbox Code Playgroud)

如果您在这种情况下不喜欢这种行为,那么最好的办法就是在您的方法中添加一个检查

void A::method(A& otherA) const {
    if (this == &otherA) { /* aliasing detected */ }
    else { /* proceed as normal */ }
}
Run Code Online (Sandbox Code Playgroud)