As, the title says:
Why is calling non virtual member function on deleted pointer an undefined behavior?
Note the Question does not ask if it is an Undefined Behavior, it asks Why it is undefined behavior.
Consider the following program:
#include<iostream>
class Myclass
{
//int i
public:
void doSomething()
{
std::cout<<"Inside doSomething";
//i = 10;
}
};
int main()
{
Myclass *ptr = new Myclass;
delete ptr;
ptr->doSomething();
return 0;
}
In the above code, the compiler does not actually dereference this
while calling member function doSomething()
. Note that the function is not an virtual function & the compilers convert the member function call to a usual function call by passing this as the first parameter to the function(As I understand this is implementation defined). They can do so because the compiler can exactly determine which function to call at compile time itself. So practically, calling the member function through deleted pointer does not dereference the this
. The this
is dereferenced only if any member is accessed inside the function body.(i.e: Uncommenting code in above example that accesses i
)
If an member is not accessed within the function there is no purpose that the above code should actually invoke undefined behavior.
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? Is it merely for sake of simplicity for users of the language that standard simply generalizes it or is there some deeper semantic involved in this mandate?
My feeling is that perhaps since it is implementation defined how compilers can invoke the member function may be that is the reason standard cannot enforce the actual point where UB occurs.
Can someone confirm?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…