Replace C-style casts to static_cast and reinterpret_cast (#5930)
* Replace C-style casts to static_cast and reinterpret_cast
Signed-off-by: cyy <cyyever@outlook.com>
* style: pre-commit fixes
---------
Signed-off-by: cyy <cyyever@outlook.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
diff --git a/include/pybind11/attr.h b/include/pybind11/attr.h
index f902c7c..b4486dc 100644
--- a/include/pybind11/attr.h
+++ b/include/pybind11/attr.h
@@ -373,7 +373,7 @@
+ (base_has_unique_ptr_holder ? "does not" : "does"));
}
- bases.append((PyObject *) base_info->type);
+ bases.append(reinterpret_cast<PyObject *>(base_info->type));
#ifdef PYBIND11_BACKWARD_COMPATIBILITY_TP_DICTOFFSET
dynamic_attr |= base_info->type->tp_dictoffset != 0;
@@ -721,7 +721,9 @@
size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs);
- return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs;
+ return named == 0
+ || (self + named + static_cast<size_t>(has_args) + static_cast<size_t>(has_kwargs))
+ == nargs;
}
PYBIND11_NAMESPACE_END(detail)
diff --git a/include/pybind11/buffer_info.h b/include/pybind11/buffer_info.h
index 75aec0b..10fa825 100644
--- a/include/pybind11/buffer_info.h
+++ b/include/pybind11/buffer_info.h
@@ -66,10 +66,11 @@
bool readonly = false)
: ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim),
shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) {
- if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size()) {
+ if (ndim != static_cast<ssize_t>(shape.size())
+ || ndim != static_cast<ssize_t>(strides.size())) {
pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length");
}
- for (size_t i = 0; i < (size_t) ndim; ++i) {
+ for (size_t i = 0; i < static_cast<size_t>(ndim); ++i) {
size *= shape[i];
}
}
@@ -195,7 +196,7 @@
template <typename T>
struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {
static bool compare(const buffer_info &b) {
- return (size_t) b.itemsize == sizeof(T)
+ return static_cast<size_t>(b.itemsize) == sizeof(T)
&& (b.format == format_descriptor<T>::value
|| ((sizeof(T) == sizeof(long))
&& b.format == (std::is_unsigned<T>::value ? "L" : "l"))
diff --git a/include/pybind11/cast.h b/include/pybind11/cast.h
index 3acb560..310b77b 100644
--- a/include/pybind11/cast.h
+++ b/include/pybind11/cast.h
@@ -394,7 +394,8 @@
}
/* Check if this is a C++ type */
- const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
+ const auto &bases
+ = all_type_info(reinterpret_cast<PyTypeObject *>(type::handle_of(h).ptr()));
if (bases.size() == 1) { // Only allowing loading from a single-value type
value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
return true;
@@ -541,7 +542,7 @@
const auto *buffer
= reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
- size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
+ size_t length = static_cast<size_t>(PYBIND11_BYTES_SIZE(utfNbytes.ptr())) / sizeof(CharT);
// Skip BOM for UTF-16/32
if (UTF_N > 8) {
buffer++;
diff --git a/include/pybind11/detail/argument_vector.h b/include/pybind11/detail/argument_vector.h
index e9bfe06..e15a3cf 100644
--- a/include/pybind11/detail/argument_vector.h
+++ b/include/pybind11/detail/argument_vector.h
@@ -231,7 +231,7 @@
new (&m_repr.hvector) typename repr_type::heap_vector(count, value);
} else {
auto &inline_arr = m_repr.iarray;
- inline_arr.arr.fill(value ? std::size_t(-1) : 0);
+ inline_arr.arr.fill(value ? static_cast<std::size_t>(-1) : 0);
inline_arr.size = static_cast<decltype(inline_arr.size)>(count);
}
}
@@ -273,9 +273,9 @@
assert(wbi.word < kWords);
assert(wbi.bit < kBitsPerWord);
if (b) {
- ha.arr[wbi.word] |= (std::size_t(1) << wbi.bit);
+ ha.arr[wbi.word] |= (static_cast<std::size_t>(1) << wbi.bit);
} else {
- ha.arr[wbi.word] &= ~(std::size_t(1) << wbi.bit);
+ ha.arr[wbi.word] &= ~(static_cast<std::size_t>(1) << wbi.bit);
}
assert(operator[](ha.size - 1) == b);
}
@@ -300,7 +300,7 @@
const auto wbi = word_and_bit_index(idx);
assert(wbi.word < kWords);
assert(wbi.bit < kBitsPerWord);
- return m_repr.iarray.arr[wbi.word] & (std::size_t(1) << wbi.bit);
+ return m_repr.iarray.arr[wbi.word] & (static_cast<std::size_t>(1) << wbi.bit);
}
PYBIND11_NOINLINE void move_to_heap_vector_with_reserved_size(std::size_t reserved_size) {
diff --git a/include/pybind11/detail/class.h b/include/pybind11/detail/class.h
index 7fe6928..21e966c 100644
--- a/include/pybind11/detail/class.h
+++ b/include/pybind11/detail/class.h
@@ -71,7 +71,7 @@
issue no Python C API calls which could potentially invoke the
garbage collector (the GC will call type_traverse(), which will in
turn find the newly constructed type in an invalid state) */
- auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
+ auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(PyType_Type.tp_alloc(&PyType_Type, 0));
if (!heap_type) {
pybind11_fail("make_static_property_type(): error allocating type!");
}
@@ -98,7 +98,7 @@
pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
}
- setattr((PyObject *) type, "__module__", str(PYBIND11_DUMMY_MODULE_NAME));
+ setattr(reinterpret_cast<PyObject *>(type), "__module__", str(PYBIND11_DUMMY_MODULE_NAME));
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
return type;
@@ -265,7 +265,7 @@
issue no Python C API calls which could potentially invoke the
garbage collector (the GC will call type_traverse(), which will in
turn find the newly constructed type in an invalid state) */
- auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
+ auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(PyType_Type.tp_alloc(&PyType_Type, 0));
if (!heap_type) {
pybind11_fail("make_default_metaclass(): error allocating metaclass!");
}
@@ -291,7 +291,7 @@
pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
}
- setattr((PyObject *) type, "__module__", str(PYBIND11_DUMMY_MODULE_NAME));
+ setattr(reinterpret_cast<PyObject *>(type), "__module__", str(PYBIND11_DUMMY_MODULE_NAME));
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
return type;
@@ -306,7 +306,7 @@
instance *self,
bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
- if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
+ if (auto *parent_tinfo = get_type_info(reinterpret_cast<PyTypeObject *>(h.ptr()))) {
for (auto &c : parent_tinfo->implicit_casts) {
if (c.first == tinfo->cpptype) {
auto *parentptr = c.second(valueptr);
@@ -530,7 +530,7 @@
issue no Python C API calls which could potentially invoke the
garbage collector (the GC will call type_traverse(), which will in
turn find the newly constructed type in an invalid state) */
- auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
+ auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(metaclass->tp_alloc(metaclass, 0));
if (!heap_type) {
pybind11_fail("make_object_base_type(): error allocating type!");
}
@@ -557,11 +557,11 @@
pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
}
- setattr((PyObject *) type, "__module__", str(PYBIND11_DUMMY_MODULE_NAME));
+ setattr(reinterpret_cast<PyObject *>(type), "__module__", str(PYBIND11_DUMMY_MODULE_NAME));
PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
- return (PyObject *) heap_type;
+ return reinterpret_cast<PyObject *>(heap_type);
}
/// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
@@ -746,7 +746,7 @@
/* Allocate memory for docstring (Python will free this later on) */
size_t size = std::strlen(rec.doc) + 1;
#if PY_VERSION_HEX >= 0x030D0000
- tp_doc = (char *) PyMem_MALLOC(size);
+ tp_doc = static_cast<char *>(PyMem_MALLOC(size));
#else
tp_doc = (char *) PyObject_MALLOC(size);
#endif
@@ -761,10 +761,10 @@
issue no Python C API calls which could potentially invoke the
garbage collector (the GC will call type_traverse(), which will in
turn find the newly constructed type in an invalid state) */
- auto *metaclass
- = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
+ auto *metaclass = rec.metaclass.ptr() ? reinterpret_cast<PyTypeObject *>(rec.metaclass.ptr())
+ : internals.default_metaclass;
- auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
+ auto *heap_type = reinterpret_cast<PyHeapTypeObject *>(metaclass->tp_alloc(metaclass, 0));
if (!heap_type) {
pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
}
@@ -777,7 +777,7 @@
auto *type = &heap_type->ht_type;
type->tp_name = full_name;
type->tp_doc = tp_doc;
- type->tp_base = type_incref((PyTypeObject *) base);
+ type->tp_base = type_incref(reinterpret_cast<PyTypeObject *>(base));
type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
if (!bases.empty()) {
type->tp_bases = bases.release().ptr();
@@ -818,18 +818,18 @@
/* Register type with the parent scope */
if (rec.scope) {
- setattr(rec.scope, rec.name, (PyObject *) type);
+ setattr(rec.scope, rec.name, reinterpret_cast<PyObject *>(type));
} else {
Py_INCREF(type); // Keep it alive forever (reference leak)
}
if (module_) { // Needed by pydoc
- setattr((PyObject *) type, "__module__", module_);
+ setattr(reinterpret_cast<PyObject *>(type), "__module__", module_);
}
PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
- return (PyObject *) type;
+ return reinterpret_cast<PyObject *>(type);
}
PYBIND11_NAMESPACE_END(detail)
diff --git a/include/pybind11/detail/cpp_conduit.h b/include/pybind11/detail/cpp_conduit.h
index a06b9b2..49c199e 100644
--- a/include/pybind11/detail/cpp_conduit.h
+++ b/include/pybind11/detail/cpp_conduit.h
@@ -21,13 +21,13 @@
return bool(internals.registered_types_py.find(type_obj)
!= internals.registered_types_py.end());
#else
- return bool(type_obj->tp_new == pybind11_object_new);
+ return (type_obj->tp_new == pybind11_object_new);
#endif
}
inline bool is_instance_method_of_type(PyTypeObject *type_obj, PyObject *attr_name) {
PyObject *descr = _PyType_Lookup(type_obj, attr_name);
- return bool((descr != nullptr) && PyInstanceMethod_Check(descr));
+ return ((descr != nullptr) && PyInstanceMethod_Check(descr));
}
inline object try_get_cpp_conduit_method(PyObject *obj) {
diff --git a/include/pybind11/detail/function_record_pyobject.h b/include/pybind11/detail/function_record_pyobject.h
index 694625f..94d27ad 100644
--- a/include/pybind11/detail/function_record_pyobject.h
+++ b/include/pybind11/detail/function_record_pyobject.h
@@ -126,7 +126,7 @@
inline function_record *function_record_ptr_from_PyObject(PyObject *obj) {
if (is_function_record_PyObject(obj)) {
- return ((detail::function_record_PyObject *) obj)->cpp_func_rec;
+ return (reinterpret_cast<detail::function_record_PyObject *>(obj))->cpp_func_rec;
}
return nullptr;
}
@@ -137,7 +137,7 @@
throw error_already_set();
}
py_func_rec->cpp_func_rec = nullptr; // For clarity/purity. Redundant in practice.
- return reinterpret_steal<object>((PyObject *) py_func_rec);
+ return reinterpret_steal<object>(reinterpret_cast<PyObject *>(py_func_rec));
}
PYBIND11_NAMESPACE_BEGIN(function_record_PyTypeObject_methods)
diff --git a/include/pybind11/detail/init.h b/include/pybind11/detail/init.h
index d7c84cb..b7f8d5a 100644
--- a/include/pybind11/detail/init.h
+++ b/include/pybind11/detail/init.h
@@ -476,9 +476,9 @@
return;
}
// Our tests never run into an unset dict, but being careful here for now (see #5658)
- auto dict = getattr((PyObject *) v_h.inst, "__dict__", none());
+ auto dict = getattr(reinterpret_cast<PyObject *>(v_h.inst), "__dict__", none());
if (dict.is_none()) {
- setattr((PyObject *) v_h.inst, "__dict__", d);
+ setattr(reinterpret_cast<PyObject *>(v_h.inst), "__dict__", d);
} else {
// Keep the original object dict and just update it
if (PyDict_Update(dict.ptr(), d.ptr()) < 0) {
diff --git a/include/pybind11/detail/internals.h b/include/pybind11/detail/internals.h
index 4d6c147..858de67 100644
--- a/include/pybind11/detail/internals.h
+++ b/include/pybind11/detail/internals.h
@@ -606,9 +606,8 @@
// this could be called without an active interpreter, just use what was cached
if (!tstate || tstate->interp == last_istate_tls()) {
auto tpp = internals_p_tls();
- if (tpp) {
- delete tpp;
- }
+
+ delete tpp;
}
unref();
return;
diff --git a/include/pybind11/detail/type_caster_base.h b/include/pybind11/detail/type_caster_base.h
index c6b8073..b0c59e1 100644
--- a/include/pybind11/detail/type_caster_base.h
+++ b/include/pybind11/detail/type_caster_base.h
@@ -125,7 +125,7 @@
assert(bases.empty());
std::vector<PyTypeObject *> check;
for (handle parent : reinterpret_borrow<tuple>(t->tp_bases)) {
- check.push_back((PyTypeObject *) parent.ptr());
+ check.push_back(reinterpret_cast<PyTypeObject *>(parent.ptr()));
}
auto const &type_dict = get_internals().registered_types_py;
for (size_t i = 0; i < check.size(); i++) {
@@ -168,7 +168,7 @@
i--;
}
for (handle parent : reinterpret_borrow<tuple>(type->tp_bases)) {
- check.push_back((PyTypeObject *) parent.ptr());
+ check.push_back(reinterpret_cast<PyTypeObject *>(parent.ptr()));
}
}
}
@@ -286,7 +286,7 @@
PYBIND11_NOINLINE handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
detail::type_info *type_info = get_type_info(tp, throw_if_missing);
- return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
+ return handle(type_info ? (reinterpret_cast<PyObject *>(type_info->type)) : nullptr);
}
inline bool try_incref(PyObject *obj) {
@@ -506,7 +506,7 @@
// efficient for small allocations like the one we're doing here;
// for larger allocations they are just wrappers around malloc.
// TODO: is this still true for pure Python 3.6?
- nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
+ nonsimple.values_and_holders = static_cast<void **>(PyMem_Calloc(space, sizeof(void *)));
if (!nonsimple.values_and_holders) {
throw std::bad_alloc();
}
@@ -537,7 +537,7 @@
for (auto it = range.first; it != range.second; ++it) {
for (const auto &vh : values_and_holders(it->second)) {
if (vh.type == type) {
- return handle((PyObject *) it->second);
+ return handle(reinterpret_cast<PyObject *>(it->second));
}
}
}
@@ -1700,7 +1700,7 @@
PYBIND11_NOINLINE std::string type_info_description(const std::type_info &ti) {
if (auto *type_data = get_type_info(ti)) {
- handle th((PyObject *) type_data->type);
+ handle th(reinterpret_cast<PyObject *>(type_data->type));
return th.attr("__module__").cast<std::string>() + '.'
+ th.attr("__qualname__").cast<std::string>();
}
diff --git a/include/pybind11/detail/value_and_holder.h b/include/pybind11/detail/value_and_holder.h
index 87c92f8..b24551e 100644
--- a/include/pybind11/detail/value_and_holder.h
+++ b/include/pybind11/detail/value_and_holder.h
@@ -54,7 +54,8 @@
} else if (v) {
inst->nonsimple.status[index] |= instance::status_holder_constructed;
} else {
- inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_holder_constructed;
+ inst->nonsimple.status[index]
+ &= static_cast<std::uint8_t>(~instance::status_holder_constructed);
}
}
bool instance_registered() const {
@@ -69,7 +70,8 @@
} else if (v) {
inst->nonsimple.status[index] |= instance::status_instance_registered;
} else {
- inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_instance_registered;
+ inst->nonsimple.status[index]
+ &= static_cast<std::uint8_t>(~instance::status_instance_registered);
}
}
};
diff --git a/include/pybind11/pybind11.h b/include/pybind11/pybind11.h
index a2043b2..91b38d9 100644
--- a/include/pybind11/pybind11.h
+++ b/include/pybind11/pybind11.h
@@ -159,7 +159,7 @@
pybind11_fail("Internal error while parsing type signature (1)");
}
if (auto *tinfo = detail::get_type_info(*t)) {
- handle th((PyObject *) tinfo->type);
+ handle th(reinterpret_cast<PyObject *>(tinfo->type));
signature += th.attr("__module__").cast<std::string>() + "."
+ th.attr("__qualname__").cast<std::string>();
} else if (auto th = detail::global_internals_native_enum_type_map_get_item(*t)) {
@@ -642,7 +642,7 @@
rec->signature = guarded_strdup(signature.c_str());
rec->args.shrink_to_fit();
- rec->nargs = (std::uint16_t) args;
+ rec->nargs = static_cast<std::uint16_t>(args);
if (rec->sibling && PYBIND11_INSTANCE_METHOD_CHECK(rec->sibling.ptr())) {
rec->sibling = PYBIND11_INSTANCE_METHOD_GET_FUNCTION(rec->sibling.ptr());
@@ -681,7 +681,7 @@
rec->def->ml_flags = METH_VARARGS | METH_KEYWORDS;
object py_func_rec = detail::function_record_PyObject_New();
- ((detail::function_record_PyObject *) py_func_rec.ptr())->cpp_func_rec
+ (reinterpret_cast<detail::function_record_PyObject *>(py_func_rec.ptr()))->cpp_func_rec
= unique_rec.release();
guarded_strdup.release();
@@ -715,8 +715,8 @@
// chain.
chain_start = rec;
rec->next = chain;
- auto *py_func_rec
- = (detail::function_record_PyObject *) PyCFunction_GET_SELF(m_ptr);
+ auto *py_func_rec = reinterpret_cast<detail::function_record_PyObject *>(
+ PyCFunction_GET_SELF(m_ptr));
py_func_rec->cpp_func_rec = unique_rec.release();
guarded_strdup.release();
} else {
@@ -776,7 +776,7 @@
}
}
- auto *func = (PyCFunctionObject *) m_ptr;
+ auto *func = reinterpret_cast<PyCFunctionObject *>(m_ptr);
// Install docstring if it's non-empty (when at least one option is enabled)
auto *doc = signatures.empty() ? nullptr : PYBIND11_COMPAT_STRDUP(signatures.c_str());
std::free(const_cast<char *>(PYBIND11_PYCFUNCTION_GET_DOC(func)));
@@ -851,7 +851,7 @@
/* Need to know how many arguments + keyword arguments there are to pick the right
overload */
- const auto n_args_in = (size_t) PyTuple_GET_SIZE(args_in);
+ const auto n_args_in = static_cast<size_t>(PyTuple_GET_SIZE(args_in));
handle parent = n_args_in > 0 ? PyTuple_GET_ITEM(args_in, 0) : nullptr,
result = PYBIND11_TRY_NEXT_OVERLOAD;
@@ -865,7 +865,8 @@
return nullptr;
}
- auto *const tinfo = get_type_info((PyTypeObject *) overloads->scope.ptr());
+ auto *const tinfo
+ = get_type_info(reinterpret_cast<PyTypeObject *>(overloads->scope.ptr()));
auto *const pi = reinterpret_cast<instance *>(parent.ptr());
self_value_and_holder = pi->get_value_and_holder(tinfo, true);
@@ -1296,7 +1297,7 @@
// This implementation needs the definition of `class cpp_function`.
inline void tp_dealloc_impl(PyObject *self) {
- auto *py_func_rec = (function_record_PyObject *) self;
+ auto *py_func_rec = reinterpret_cast<function_record_PyObject *>(self);
cpp_function::destruct(py_func_rec->cpp_func_rec);
py_func_rec->cpp_func_rec = nullptr;
}
@@ -1669,7 +1670,7 @@
/* Register supplemental type information in C++ dict */
auto *tinfo = new detail::type_info();
- tinfo->type = (PyTypeObject *) m_ptr;
+ tinfo->type = reinterpret_cast<PyTypeObject *>(m_ptr);
tinfo->cpptype = rec.type;
tinfo->type_size = rec.type_size;
tinfo->type_align = rec.type_align;
@@ -1704,7 +1705,7 @@
PYBIND11_WARNING_DISABLE_GCC("-Warray-bounds")
PYBIND11_WARNING_DISABLE_GCC("-Wstringop-overread")
#endif
- internals.registered_types_py[(PyTypeObject *) m_ptr] = {tinfo};
+ internals.registered_types_py[reinterpret_cast<PyTypeObject *>(m_ptr)] = {tinfo};
PYBIND11_WARNING_POP
});
@@ -1712,7 +1713,8 @@
mark_parents_nonsimple(tinfo->type);
tinfo->simple_ancestors = false;
} else if (rec.bases.size() == 1) {
- auto *parent_tinfo = get_type_info((PyTypeObject *) rec.bases[0].ptr());
+ auto *parent_tinfo
+ = get_type_info(reinterpret_cast<PyTypeObject *>(rec.bases[0].ptr()));
assert(parent_tinfo != nullptr);
bool parent_simple_ancestors = parent_tinfo->simple_ancestors;
tinfo->simple_ancestors = parent_simple_ancestors;
@@ -1731,17 +1733,17 @@
void mark_parents_nonsimple(PyTypeObject *value) {
auto t = reinterpret_borrow<tuple>(value->tp_bases);
for (handle h : t) {
- auto *tinfo2 = get_type_info((PyTypeObject *) h.ptr());
+ auto *tinfo2 = get_type_info(reinterpret_cast<PyTypeObject *>(h.ptr()));
if (tinfo2) {
tinfo2->simple_type = false;
}
- mark_parents_nonsimple((PyTypeObject *) h.ptr());
+ mark_parents_nonsimple(reinterpret_cast<PyTypeObject *>(h.ptr()));
}
}
void install_buffer_funcs(buffer_info *(*get_buffer)(PyObject *, void *),
void *get_buffer_data) {
- auto *type = (PyHeapTypeObject *) m_ptr;
+ auto *type = reinterpret_cast<PyHeapTypeObject *>(m_ptr);
auto *tinfo = detail::get_type_info(&type->ht_type);
if (!type->ht_type.tp_as_buffer) {
@@ -1763,8 +1765,8 @@
const auto is_static = (rec_func != nullptr) && !(rec_func->is_method && rec_func->scope);
const auto has_doc = (rec_func != nullptr) && (rec_func->doc != nullptr)
&& pybind11::options::show_user_defined_docstrings();
- auto property = handle(
- (PyObject *) (is_static ? get_internals().static_property_type : &PyProperty_Type));
+ auto property = handle(reinterpret_cast<PyObject *>(
+ is_static ? get_internals().static_property_type : &PyProperty_Type));
attr(name) = property(fget.ptr() ? fget : none(),
fset.ptr() ? fset : none(),
/*deleter*/ none(),
@@ -2698,8 +2700,9 @@
PYBIND11_NOINLINE void init(bool is_arithmetic, bool is_convertible) {
m_base.attr("__entries") = dict();
- auto property = handle((PyObject *) &PyProperty_Type);
- auto static_property = handle((PyObject *) get_internals().static_property_type);
+ auto property = handle(reinterpret_cast<PyObject *>(&PyProperty_Type));
+ auto static_property
+ = handle(reinterpret_cast<PyObject *>(get_internals().static_property_type));
m_base.attr("__repr__") = cpp_function(
[](const object &arg) -> str {
@@ -2730,7 +2733,7 @@
[](handle arg) -> std::string {
std::string docstring;
dict entries = arg.attr("__entries");
- if (((PyTypeObject *) arg.ptr())->tp_doc) {
+ if ((reinterpret_cast<PyTypeObject *>(arg.ptr()))->tp_doc) {
docstring += std::string(
reinterpret_cast<PyTypeObject *>(arg.ptr())->tp_doc);
docstring += "\n\n";
@@ -2856,7 +2859,7 @@
dict entries = m_base.attr("__entries");
str name(name_);
if (entries.contains(name)) {
- std::string type_name = (std::string) str(m_base.attr("__name__"));
+ std::string type_name = std::string(str(m_base.attr("__name__")));
throw value_error(std::move(type_name) + ": element \"" + std::string(name_)
+ "\" already exists!");
}
@@ -3051,7 +3054,7 @@
if (res.second) {
// New cache entry created; set up a weak reference to automatically remove it if the type
// gets destroyed:
- weakref((PyObject *) type, cpp_function([type](handle wr) {
+ weakref(reinterpret_cast<PyObject *>(type), cpp_function([type](handle wr) {
with_internals([type](internals &internals) {
internals.registered_types_py.erase(type);
@@ -3292,7 +3295,7 @@
}
tuple args(1);
args[0] = obj;
- PyObject *result = PyObject_Call((PyObject *) type, args.ptr(), nullptr);
+ PyObject *result = PyObject_Call(reinterpret_cast<PyObject *>(type), args.ptr(), nullptr);
if (result == nullptr) {
PyErr_Clear();
}
@@ -3508,7 +3511,7 @@
if (frame != nullptr) {
PyCodeObject *f_code = PyFrame_GetCode(frame);
// f_code is guaranteed to not be NULL
- if ((std::string) str(f_code->co_name) == name && f_code->co_argcount > 0) {
+ if (std::string(str(f_code->co_name)) == name && f_code->co_argcount > 0) {
# if PY_VERSION_HEX >= 0x030d0000
PyObject *locals = PyEval_GetFrameLocals();
# else
diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h
index b28692f..538ee1c 100644
--- a/include/pybind11/pytypes.h
+++ b/include/pybind11/pytypes.h
@@ -547,7 +547,7 @@
// The presence of __notes__ is likely due to exception normalization
// errors, although that is not necessarily true, therefore insert a
// hint only:
- if (PyObject_HasAttrString(m_value.ptr(), "__notes__")) {
+ if (PyObject_HasAttrString(m_value.ptr(), "__notes__") != 0) {
m_lazy_error_string += "[WITH __notes__]";
}
#else
@@ -1563,7 +1563,9 @@
PYBIND11_OBJECT(type, object, PyType_Check)
/// Return a type handle from a handle or an object
- static handle handle_of(handle h) { return handle((PyObject *) Py_TYPE(h.ptr())); }
+ static handle handle_of(handle h) {
+ return handle(reinterpret_cast<PyObject *>(Py_TYPE(h.ptr())));
+ }
/// Return a type object from a handle or an object
static type of(handle h) { return type(type::handle_of(h), borrowed_t{}); }
@@ -1661,7 +1663,7 @@
if (PyBytes_AsStringAndSize(temp.ptr(), &buffer, &length) != 0) {
throw error_already_set();
}
- return std::string(buffer, (size_t) length);
+ return std::string(buffer, static_cast<size_t>(length));
}
template <typename... Args>
@@ -1861,10 +1863,12 @@
Unsigned as_unsigned(PyObject *o) {
if (sizeof(Unsigned) <= sizeof(unsigned long)) {
unsigned long v = PyLong_AsUnsignedLong(o);
- return v == (unsigned long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
+ return v == static_cast<unsigned long>(-1) && PyErr_Occurred() ? (Unsigned) -1
+ : (Unsigned) v;
}
unsigned long long v = PyLong_AsUnsignedLongLong(o);
- return v == (unsigned long long) -1 && PyErr_Occurred() ? (Unsigned) -1 : (Unsigned) v;
+ return v == static_cast<unsigned long long>(-1) && PyErr_Occurred() ? (Unsigned) -1
+ : (Unsigned) v;
}
PYBIND11_NAMESPACE_END(detail)
@@ -1908,7 +1912,7 @@
PYBIND11_OBJECT_CVT(float_, object, PyFloat_Check, PyNumber_Float)
// Allow implicit conversion from float/double:
// NOLINTNEXTLINE(google-explicit-constructor)
- float_(float value) : object(PyFloat_FromDouble((double) value), stolen_t{}) {
+ float_(float value) : object(PyFloat_FromDouble(static_cast<double>(value)), stolen_t{}) {
if (!m_ptr) {
pybind11_fail("Could not allocate float object!");
}
@@ -1920,7 +1924,7 @@
}
}
// NOLINTNEXTLINE(google-explicit-constructor)
- operator float() const { return (float) PyFloat_AsDouble(m_ptr); }
+ operator float() const { return static_cast<float>(PyFloat_AsDouble(m_ptr)); }
// NOLINTNEXTLINE(google-explicit-constructor)
operator double() const { return PyFloat_AsDouble(m_ptr); }
};
@@ -2122,7 +2126,7 @@
pybind11_fail("Could not allocate tuple object!");
}
}
- size_t size() const { return (size_t) PyTuple_Size(m_ptr); }
+ size_t size() const { return static_cast<size_t>(PyTuple_Size(m_ptr)); }
bool empty() const { return size() == 0; }
detail::tuple_accessor operator[](size_t index) const { return {*this, index}; }
template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
@@ -2156,7 +2160,7 @@
typename collector = detail::deferred_t<detail::unpacking_collector<>, Args...>>
explicit dict(Args &&...args) : dict(collector(std::forward<Args>(args)...).kwargs()) {}
- size_t size() const { return (size_t) PyDict_Size(m_ptr); }
+ size_t size() const { return static_cast<size_t>(PyDict_Size(m_ptr)); }
bool empty() const { return size() == 0; }
detail::dict_iterator begin() const { return {*this, 0}; }
detail::dict_iterator end() const { return {}; }
@@ -2176,7 +2180,8 @@
if (PyDict_Check(op)) {
return handle(op).inc_ref().ptr();
}
- return PyObject_CallFunctionObjArgs((PyObject *) &PyDict_Type, op, nullptr);
+ return PyObject_CallFunctionObjArgs(
+ reinterpret_cast<PyObject *>(&PyDict_Type), op, nullptr);
}
};
@@ -2188,7 +2193,7 @@
if (result == -1) {
throw error_already_set();
}
- return (size_t) result;
+ return static_cast<size_t>(result);
}
bool empty() const { return size() == 0; }
detail::sequence_accessor operator[](size_t index) const { return {*this, index}; }
@@ -2211,7 +2216,7 @@
pybind11_fail("Could not allocate list object!");
}
}
- size_t size() const { return (size_t) PyList_Size(m_ptr); }
+ size_t size() const { return static_cast<size_t>(PyList_Size(m_ptr)); }
bool empty() const { return size() == 0; }
detail::list_accessor operator[](size_t index) const { return {*this, index}; }
template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
@@ -2497,7 +2502,7 @@
if (result < 0) {
throw error_already_set();
}
- return (size_t) result;
+ return static_cast<size_t>(result);
}
/// Get the length hint of a Python object.
@@ -2510,7 +2515,7 @@
PyErr_Clear();
return 0;
}
- return (size_t) result;
+ return static_cast<size_t>(result);
}
inline str repr(handle h) {