First, keep in mind that the ->
operator of auto_ptr
is essentially forwarded on to the contained pointer. So for this discussion, your code in main
becomes equivalent to:
MyClass* ptr = NULL;
cout << ptr->solution() << endl;
Then note that compilers tend to implement member functions in ways that act very much as if they were non-member functions with the this
pointer passed as another function argument. So from your current compiler's point of view, your code in main
acts as if it was:
MyClass* ptr = NULL;
cout << solution(ptr) << endl;
with solution written as:
int solution(MyClass* this) { return 42; }
In which case it becomes obvious why there wasn't a crash.
However as others have already mentioned, these are internal details of how compilers implement C++, which are not specified by the language standard. So in theory this code could work as described here on one compiler but crash or do something else entirely on another compiler.
But in practice, even if the standard doesn't guarantee this behavior, any particular compiler could guarantee it if they want to. For instance: since MFC relies on this behavior, it is very unlikely that Visual Studio will ever stop supporting it. Of course, you would have to research each particular compiler where your code might be used to make sure that they actually guarantee this behavior.