cppcoreguidelines-pro-type-union-access

According to https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md using union for type-punning is undefined behaviour.
 Replace it with std::memcpy
This commit is contained in:
wmayer
2022-06-24 14:29:50 +02:00
parent a0807918a0
commit f5235a8057
12 changed files with 46 additions and 59 deletions

View File

@@ -513,8 +513,7 @@ void InterpreterSingleton::addType(PyTypeObject* Type,PyObject* Module, const ch
// This function is responsible for adding inherited slots from a type's base class.
if (PyType_Ready(Type) < 0)
return;
union PyType_Object pyType = {Type};
PyModule_AddObject(Module, Name, pyType.o);
PyModule_AddObject(Module, Name, Base::getTypeAsObject(Type));
}
void InterpreterSingleton::addPythonPath(const char* Path)

View File

@@ -47,6 +47,7 @@
#endif
#define slots
#include <bitset>
#include <cstring>
#include "Exception.h"
#ifndef PYCXX_PYTHON_2TO3
@@ -90,15 +91,6 @@
#define PyMOD_INIT_FUNC(name) PyMODINIT_FUNC PyInit_##name(void)
#define PyMOD_Return(name) return name
/**
* Union to convert from PyTypeObject to PyObject pointer.
*/
union PyType_Object {
PyTypeObject *t;
PyObject *o;
};
/*------------------------------
* Basic defines
@@ -122,6 +114,14 @@ inline void Assert(int expr, char *msg) // C++ assert
};
}
inline PyObject* getTypeAsObject(PyTypeObject* type) {
// See https://en.cppreference.com/w/cpp/string/byte/memcpy
// and https://en.cppreference.com/w/cpp/language/reinterpret_cast
PyObject* obj;
std::memcpy(&obj, &type, sizeof type);
return obj;
}
}
/*------------------------------

View File

@@ -595,8 +595,7 @@ Py::Object QuantityPy::getUnit() const
void QuantityPy::setUnit(Py::Object arg)
{
union PyType_Object pyType = {&(Base::UnitPy::Type)};
Py::Type UnitType(pyType.o);
Py::Type UnitType(Base::getTypeAsObject(&Base::UnitPy::Type));
if(!arg.isType(UnitType))
throw Py::AttributeError("Not yet implemented");

View File

@@ -96,8 +96,7 @@ PyObject* VectorPy::__reduce__(PyObject *args)
Py::Tuple tuple(2);
union PyType_Object pyType = {&VectorPy::Type};
Py::Object type(pyType.o);
Py::Object type(Base::getTypeAsObject(&Base::VectorPy::Type));
tuple.setItem(0, type);
Base::Vector3d v = this->value();