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?

4
  • stackoverflow.com/questions/2474018/… Commented Oct 1, 2018 at 8: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. Commented Oct 1, 2018 at 8: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. Commented Oct 1, 2018 at 8:36
  • Thanks, I forgot about optimization. I'll add that to the comment. Commented Oct 1, 2018 at 8:39

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I found this on cppreference: Null pointers: dereferencing a null pointer is undefined behavior.
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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.