if (!this) is allowed?

23 views
Skip to first unread message

Александр Гурьянов

unread,
Feb 25, 2021, 1:57:58 AM2/25/21
to emscripte...@googlegroups.com
Hi, I have a big code base that uses this pattern:

```
int String::intValue() const {
if (!this) {
return 0;
}

// ...
}

int count = dict->stringForKey("count")->intValue();
```

If dict->stringForKey returns nullptr then wasm is crashed, but native works fine.
This code also worked fine with old versions of emscipten.

I understand that this is ugly pattern, but I am curious if it can work as before?

Thomas Lively

unread,
Feb 25, 2021, 2:17:55 AM2/25/21
to emscripte...@googlegroups.com
I’m pretty sure that calling a method on a null pointer is undefined behavior. My guess is that at some point LLVM started recognizing and optimizing away this UB, which is why you’re seeing different behavior with newer versions of Emscripten.

--
You received this message because you are subscribed to the Google Groups "emscripten-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to emscripten-disc...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/emscripten-discuss/CAKOm%3DVF2kSJEthLuvS7afsPFprxehG%3DXJxppdHxMA6a8rvUyAw%40mail.gmail.com.

Sam Clegg

unread,
Feb 25, 2021, 11:49:38 AM2/25/21
to emscripte...@googlegroups.com
Reminds me of why `this` should really be a reference and not a pointer: https://www.stroustrup.com/bs_faq2.html#this

Floh

unread,
Feb 26, 2021, 7:45:42 AM2/26/21
to emscripten-discuss
Godbolt is great for checking stuff like this:


Clang should give a warning (even without evelated warning level), and the undefined behaviour sanitizer also complains.

Since this is C++ anyway (not C), I've seen a nice solution for this type of stuff in TinyXML2, a special special pointer wrapper class which allows safe method chaining, see here:

Reply all
Reply to author
Forward
0 new messages