Skip to content

Commit fc8ca60

Browse files
committed
Make the const-removal clearly visible. This simplifies the production code changes significantly.
For background see: https://claude.ai/share/4085d9ab-a859-44cc-bb56-450e472f817a
1 parent 51a1942 commit fc8ca60

File tree

2 files changed

+7
-13
lines changed

2 files changed

+7
-13
lines changed

include/pybind11/detail/init.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,12 @@ void construct(value_and_holder &v_h, Holder<Class> holder, bool need_alias) {
167167
"is not an alias instance");
168168
}
169169

170-
v_h.value_ptr<typename std::remove_pointer<decltype(ptr)>::type>() = ptr;
170+
// Cast away constness to store in void* storage.
171+
// The value_and_holder storage is fundamentally untyped (void**), so we lose
172+
// const-correctness here by design. The const qualifier will be restored
173+
// when the pointer is later retrieved and cast back to the original type.
174+
// This explicit const_cast makes the const-removal clearly visible.
175+
v_h.value_ptr() = const_cast<void *>(static_cast<const void *>(ptr));
171176
v_h.type->init_instance(v_h.inst, &holder);
172177
}
173178

include/pybind11/detail/value_and_holder.h

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ struct value_and_holder {
3333

3434
template <typename V = void>
3535
V *&value_ptr() const {
36-
return cast_void<V>(vh[0]);
36+
return reinterpret_cast<V *&>(vh[0]);
3737
}
3838
// True if this `value_and_holder` has a non-null value pointer
3939
explicit operator bool() const { return value_ptr() != nullptr; }
@@ -72,17 +72,6 @@ struct value_and_holder {
7272
inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_instance_registered;
7373
}
7474
}
75-
76-
private:
77-
template <typename V, detail::enable_if_t<!std::is_const<V>::value, bool> = true>
78-
static V *&cast_void(void *&ptr) {
79-
return reinterpret_cast<V *&>(ptr);
80-
}
81-
82-
template <typename V, detail::enable_if_t<std::is_const<V>::value, bool> = true>
83-
static V *&cast_void(void *&ptr) {
84-
return reinterpret_cast<V *&>(const_cast<const void *&>(ptr));
85-
}
8675
};
8776

8877
// This is a semi-public API to check if the corresponding instance has been constructed with a

0 commit comments

Comments
 (0)