且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在已删除的指针上调用非虚拟成员函数是未定义的行为?

更新时间:2023-11-12 22:27:10

那么为什么标准要求通过删除的指针调用非虚拟成员函数是未定义的行为,而实际上却可以可靠地说,取消引用this应该是导致未定义行为的语句?

So why does the standard mandate that calling the non virtual member function through deleted pointer is an undefined behavior, when in fact it can reliably say that dereferencing the this should be the statement which should cause undefined behavior?

[expr.ref]第2段说,诸如ptr->doSomething()之类的成员函数调用等同于(*ptr).doSomething(),因此调用非静态成员函数 是取消引用.如果指针无效,则表示行为不确定.

[expr.ref] paragraph 2 says that a member function call such as ptr->doSomething() is equivalent to (*ptr).doSomething() so calling a non-static member function is a dereference. If the pointer is invalid that's undefined behaviour.

在特定情况下,生成的代码实际上是否需要取消引用指针无关紧要,编译器模型执行的抽象机器原则上也进行取消引用.

Whether the generated code actually needs to dereference the pointer for specific cases is not relevant, the abstract machine that the compiler models does do a dereference in principle.

复杂化语言以准确定义允许哪些案例(只要它们不访问任何成员)将带来几乎为零的收益.在看不到函数定义的情况下,您不知道调用它是否安全,因为您不知道该函数是否使用this.

Complicating the language to define exactly which cases would be allowed as long as they don't access any members would have almost zero benefit. In the case where you can't see the function definition you have no idea if calling it would be safe, because you can't know if the function uses this or not.

只是不要这样做,没有充分的理由,而且语言禁止这样做是一件好事.

Just don't do it, there's no good reason to, and it's a Good Thing that the language forbids it.