1

In short, the question is: if I call a no-op function on a null pointer is that UB?

Roughly speaking, I want to make a lightweight class which just becomes no-ops depending on build flags. For example:

class RealObject {
  void foo() { /* do something real*/ }
};

class DummyObject {
  inline void foo() {}
};

#ifdef DO_REAL
RealObject* obj = new Object();
#else
DummyObject* obj = nullptr;
#endif

obj->foo();

My gut tells me in the case where DummyObject gets used it violates something in the standard (don't what exactly what) but since foo() is no-op in practice it still could work as expected.

Can someone clarify the rules in this situation? thanks

ryan0270
  • 1,135
  • 11
  • 33
  • In short and formally? Yes. Practically? I don't know an implementation that does something nasty with this. – StoryTeller - Unslander Monica Sep 26 '17 at 13:38
  • Why do you need to invoke anything if you are using macro anyway? – Slava Sep 26 '17 at 13:39
  • @Slava This is a just a toy example to get the point across. – ryan0270 Sep 26 '17 at 13:42
  • 2
    If you want sometime like to to become pretty close to a no-op but remain defined behavior you might consider making the `DummyObject` variation point to a statically allocated singleton: `static DummyObject do_singleton; ... ; DummyObject* obj = &do_singleton;`. In optimization the compiler should elide all calls, the linker might even be able to remove the do-nothing object as well. – Michael Burr Sep 26 '17 at 14:13
  • I think this is an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Why did you came up with this solution? _What are you trying to achieve?_ – YSC Sep 26 '17 at 14:14
  • You can create a thin wrapper for a pointer to `RealObject` and use it instead. – Slava Sep 26 '17 at 15:13

0 Answers0