wlav / cppyy

Other
387 stars 39 forks source link

Types with operator bool() won't check for nullptr #186

Closed mkolin closed 8 months ago

mkolin commented 11 months ago

When a type has an operator bool() method, cppyy doesn't seem to check for nullptr and will throw.

>>> import cppyy
>>> cppyy.cppdef('''
... struct Test1 { };
... struct Test2 { explicit operator bool() const { return true; } }; 
... Test1* CreateTest1() { return nullptr; }
... Test2* CreateTest2() { return nullptr; }
... ''')
True
>>> from cppyy.gbl import CreateTest1, CreateTest2
>>> t = CreateTest1()
>>> if t:
...   print('valid')
... 
>>> t = CreateTest2()
>>> if t:
...   print('valid')
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ReferenceError: attempt to access a null-pointer

It would be nice if we can check for nullptr and then call the operator bool() to ensure we don't get a ReferenceError exception.

Tested with cppyy 2.4.2

wlav commented 11 months ago

I see ... two different code paths. The first goes to the default __bool__ implementation (__nonzero__) which is a Python method and does internally a null check to determine True or False. In the second case, operator bool() is mapped to __bool__, making it a C++ method, in which case the null check is performed before calling the method (to prevent segfaults), hence the ReferenceError (just like for any other C++ method).

It's probably reasonable to treat __bool__ as a special case.

wlav commented 11 months ago

Fixed in repo.

wlav commented 8 months ago

Released with release 3.1.0.