nb::ref<T>, std::shared<T> and T* allow casting from None if elements of a container like std::vector<nb::ref<T>> #1060
Unanswered
ramenguy99
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, I am using types like
std::vector<nb::ref<T>>
as function arguments in multiple places. I just noticed thatnb::ref
and other pointer types likestd::shared_ptr<T>
andT*
implicitly allow casting from the pythonNone
object when used inside containers.For example:
can be called with:
The same cast is also allowed for other containers like
std::tuple
andstd::array
.From a quick look at the call stack of this cast it looks like the cast to null is allowed by:
nanobind/src/nb_type.cpp
Lines 1490 to 1496 in 109af19
This can make it quite inconvenient because it requires checks in multiple places if elements of container objects are actually null pointers, risking null derefs if this is forgot. Due to the default policy of not implicitly casting
None
to pointer types for function arguments I would have expected the same rule to apply here, and require something likestd::vector<std::optional<nb::ref<T>>>
ifNone
is acceptable.Another option would be to have an additional reference type that is more strict with casting and would not allow
None
, something likeNonNullRef<T>
, but I am not sure if this would be preferred. In my (limited) experience I almost always wantnb::ref
to not be null in the first place.Is there a recommended way to disallow
None
for this kind of use case?Beta Was this translation helpful? Give feedback.
All reactions