0

I would like to replace code like this:

if ((obj != nullptr) && obj->is_valid())

with

if (obj->is_valid())

where

class Obj {
    bool is_valid() {
        if (this == nullptr)
            return false;
        // some more logic ...
    }
    ...
};

Obviously there are 2 conditions:

  1. obj is always accessed via pointer
  2. Obj::is_valid() is never virtual

This is based on the fact, that a non-virtual method accepts this as its 1-st argument, so that

obj->is_valid();

is rewritten as

Obj::is_valid(obj);

While this code does work as expected with gcc-5.4.0, my question is whether this is a legitimate C++ code, that will be interpreted / optimized correctly by other (older / newer) C++ compilers?

segfault
  • 489
  • 4
  • 16
  • https://stackoverflow.com/questions/2474018/when-does-invoking-a-member-function-on-a-null-instance-result-in-undefined-beha?noredirect=1&lq=1 – Mat Oct 01 '18 at 08:33
  • It's going to do what you expect it to do nearly everywhere (without any optimization at least), but there's no guarantee, as it is undefined behavior. – Blaze Oct 01 '18 at 08:34
  • 3
    @Blaze It won't on newer versions of gcc with optimization enabled. That's why answers belong in the answer section, not in comments, so we can downvote misinformation like that. – Baum mit Augen Oct 01 '18 at 08:36
  • Thanks, I forgot about optimization. I'll add that to the comment. – Blaze Oct 01 '18 at 08:39

1 Answers1

6

Don't.

if (this == nullptr)

It would not provide any security as calling a member function (method) on a null pointer is undefined behavior in the first place. This is bringing a sensation of security without the security, which is worse than nothing.

YSC
  • 38,212
  • 9
  • 96
  • 149
  • I found this on [cppreference: Null pointers](https://en.cppreference.com/w/cpp/language/pointer#Null_pointers): _dereferencing a null pointer is undefined behavior_. – Scheff's Cat Oct 01 '18 at 08:35
  • While reading (and upvoting) your answer, I was searching for something like an "authoritative" source... (and thought, it might be worth to provide the link to cppreference I found). – Scheff's Cat Oct 01 '18 at 12:51