|
|
|
|
|
by jrziviani
3735 days ago
|
|
It's possible to have 'this' == NULL. Consider the code: #include <iostream>
using namespace std;
class myclass
{
public:
int sum(int a, int b)
{
cout << this << endl;
return a + b;
}
};
int main()
{
cout << ((myclass*)0)->sum(10, 11) << endl;
return 0;
}
this will print:
0
21And it's not a null pointer dereference because in C++ it's the function responsible to know the class its belongs to. It means that this code: ((myclass*)0)->sum(10, 11)
should become: sum(0 /*this*/, 10, 11)
and not 0->sum(10, 11)
It can be UB in the C++ specification, but considering the systemv abi, 'this' is just a parameter that will be pushed in the call stack before calling 'sum'. |
|
First, within myclass::sum, the compiler can assume that "this" will never be null. In your example, you pass "this" to cout; if the iostream code is inlined, and it has a conditional on the passed pointer, for instance to special-case the output of a null pointer, the compiler will omit the comparison and output only the code for the non-null case.
Second, within the main function. The compiler can see you are calling a method with a null "this" pointer. Since this is undefined behavior, it clearly can't happen, and there must be something earlier in the call path that leads to that part of the code never being executed. Therefore, since this is the first thing in the main function, the compiler can assume that main() will never be called, and replace it with an empty function (to satisfy the linker).
If your compiler doesn't do that, it only means that it's not smart enough yet. The behavior can change in later versions of your compiler, or if you use a different compiler.