On Dec 2, 2015, at 3:32 PM, Jens Alfke < email@hidden> wrote:
On Dec 2, 2015, at 12:00 PM, Jonathan Prescott < email@hidden> wrote:
In C++, “this” is a read-only (const) pointer setup during construction of the instance. Once an instance of a class is successfully created, the “this” pointer is guaranteed to be non-null for the lifetime of the instance.
No. It’s not a _part of_ the instance, it’s a _pointer to_ the instance. It only exists as an invisible parameter passed to a method.
For example, the method foo::method(int x) is internally implemented as a function [with a mangled name] that takes a parameter list (foo *this, int x). And calling f->method(1) is exactly like calling that function with parameter list (f, 1). Assuming the method is non-virtual. If it’s virtual, this gets more complicated. I tried out a couple of ways of trying to modify the “this" pointer of an existing class instance, and the clang and gcc compilers would not allow that operation to compile.
Again, ‘this’ doesn’t belong to the instance. It’s simply a function parameter. Here’s a simple way to call a method with a NULL ‘this’:
struct foo { void method() { printf(“this = %p\n”, this); } }
foo *f = NULL; f->method();
—Jens
Hey Jens,
Maybe you could give us more info about what your code is trying to accomplish and what the workaround you intend.
From what I can tell from the small code snippet, you want to add special case code to a C++ method that detects calling into an object using a NULL pointer, and turn this into a non-crashing condition. The problem seems to be that you can make up C++ code that constructs a NULL pointer and then crash when you dereference it. My understanding is that the C++ spec unequivocally defines this as an error and therefor it shouldn’t be happening at all. If this is what your code is attempting to workaround, my thinking is to fix the coding error at the source rather than after the fact (e.g. method implementation). Adding code to the method implementation seems like the wrong place to identify/work around this error. I’m kind of on the side of the clang developers on this one, the warning make some good sense.
Obviously the NULL pointer problem in C++ is a cluster-f and has no general solution (other than “don’t do that”). FWIW, C++ references have similar problems, in that historically you could make up code to construct an invalid reference and then crash using it. So I can appreciate wanting to find ways to make this a non-terminal bug. I think the MS compiler used to turn your crasher into an exception via a compiler flag, which seemed like a pretty good, albeit non-portable, solution. I had some ideas of coming up with an overloaded dereference operator that would do a NULL check but you quickly realize the performance and portability issues with doing it aren’t worth it.
Anyways, let us know how this gets worked out for you.
Doug Hill /Glad I’m not doing C++ any more |