Why is calling non virtual member function on deleted pointer an undefined behavior?

后端 未结 4 936
醉话见心
醉话见心 2020-12-11 23:29

As, the title says:

Why is calling non virtual member function on deleted pointer an undefined behavior?

Note the

4条回答
  •  悲&欢浪女
    2020-12-12 00:25

    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] 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.

    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.

提交回复
热议问题