diff --git a/.clang-tidy b/.clang-tidy index b800bcb21c..38f21b8bfc 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -152,7 +152,7 @@ CheckOptions: - key: google-readability-braces-around-statements.ShortStatementLines value: '1' - key: bugprone-reserved-identifier.AllowedIdentifiers - value: '' + value: '_object;_Precision' - key: cppcoreguidelines-pro-type-member-init.IgnoreArrays value: 'false' - key: readability-else-after-return.WarnOnUnfixable diff --git a/src/Base/Axis.cpp b/src/Base/Axis.cpp index 45959d991b..8c0450906c 100644 --- a/src/Base/Axis.cpp +++ b/src/Base/Axis.cpp @@ -38,9 +38,9 @@ void Axis::reverse() Axis Axis::reversed() const { - Axis a(*this); - a.reverse(); - return a; + Axis axis(*this); + axis.reverse(); + return axis; } void Axis::move(const Vector3d& MovVec) @@ -58,16 +58,16 @@ bool Axis::operator!=(const Axis& that) const return !(*this == that); } -Axis& Axis::operator*=(const Placement& p) +Axis& Axis::operator*=(const Placement& plm) { - p.multVec(this->_base, this->_base); - p.getRotation().multVec(this->_dir, this->_dir); + plm.multVec(this->_base, this->_base); + plm.getRotation().multVec(this->_dir, this->_dir); return *this; } -Axis Axis::operator*(const Placement& p) const +Axis Axis::operator*(const Placement& plm) const { - Axis a(*this); - a *= p; - return a; + Axis axis(*this); + axis *= plm; + return axis; } diff --git a/src/Base/Axis.h b/src/Base/Axis.h index b0ef8b04b3..b7bac366e0 100644 --- a/src/Base/Axis.h +++ b/src/Base/Axis.h @@ -67,8 +67,8 @@ public: /** Operators. */ //@{ - Axis& operator*=(const Placement& p); - Axis operator*(const Placement& p) const; + Axis& operator*=(const Placement& plm); + Axis operator*(const Placement& plm) const; bool operator==(const Axis&) const; bool operator!=(const Axis&) const; Axis& operator=(const Axis&) = default; diff --git a/src/Base/AxisPyImp.cpp b/src/Base/AxisPyImp.cpp index 57de505bf5..9c652ba75b 100644 --- a/src/Base/AxisPyImp.cpp +++ b/src/Base/AxisPyImp.cpp @@ -47,7 +47,7 @@ std::string AxisPy::representation() const return str.str(); } -PyObject* AxisPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper +PyObject* AxisPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { // create a new instance of AxisPy and the Twin object return new AxisPy(new Axis); diff --git a/src/Base/BaseClass.cpp b/src/Base/BaseClass.cpp index 2d6f024aca..301cb5c33b 100644 --- a/src/Base/BaseClass.cpp +++ b/src/Base/BaseClass.cpp @@ -106,11 +106,8 @@ void BaseClass::initSubclass(Base::Type& toInit, */ PyObject* BaseClass::getPyObject() { - assert(0); Py_Return; } -void BaseClass::setPyObject(PyObject*) -{ - assert(0); -} +void BaseClass::setPyObject(PyObject* /*unused*/) +{} diff --git a/src/Base/BaseClass.h b/src/Base/BaseClass.h index 3de71239de..d1adc97602 100644 --- a/src/Base/BaseClass.h +++ b/src/Base/BaseClass.h @@ -30,6 +30,7 @@ using PyObject = struct _object; +// NOLINTBEGIN(cppcoreguidelines-macro-usage) /// define for subclassing Base::BaseClass #define TYPESYSTEM_HEADER() \ public: \ @@ -129,6 +130,7 @@ private: { \ initSubclass(_class_::classTypeId, #_class_, #_parentclass_, &(_class_::create)); \ } +// NOLINTEND(cppcoreguidelines-macro-usage) namespace Base { @@ -191,14 +193,13 @@ public: * */ template -T* freecad_dynamic_cast(Base::BaseClass* t) +T* freecad_dynamic_cast(Base::BaseClass* type) { - if (t && t->isDerivedFrom(T::getClassTypeId())) { - return static_cast(t); - } - else { - return nullptr; + if (type && type->isDerivedFrom(T::getClassTypeId())) { + return static_cast(type); } + + return nullptr; } /** @@ -207,14 +208,13 @@ T* freecad_dynamic_cast(Base::BaseClass* t) * */ template -const T* freecad_dynamic_cast(const Base::BaseClass* t) +const T* freecad_dynamic_cast(const Base::BaseClass* type) { - if (t && t->isDerivedFrom(T::getClassTypeId())) { - return static_cast(t); - } - else { - return nullptr; + if (type && type->isDerivedFrom(T::getClassTypeId())) { + return static_cast(type); } + + return nullptr; } diff --git a/src/Base/Bitmask.h b/src/Base/Bitmask.h index 1c6c0792b9..cae10e6bee 100644 --- a/src/Base/Bitmask.h +++ b/src/Base/Bitmask.h @@ -44,6 +44,7 @@ @endcode */ +// NOLINTBEGIN // clang-format off // Based on https://stackoverflow.com/questions/1448396/how-to-use-enums-as-flags-in-c template struct enum_traits {}; @@ -130,5 +131,6 @@ public: }; } // clang-format on +// NOLINTEND #endif diff --git a/src/Base/BoundBoxPyImp.cpp b/src/Base/BoundBoxPyImp.cpp index 1f5e1c7282..a3fecb25ef 100644 --- a/src/Base/BoundBoxPyImp.cpp +++ b/src/Base/BoundBoxPyImp.cpp @@ -45,7 +45,7 @@ std::string BoundBoxPy::representation() const return str.str(); } -PyObject* BoundBoxPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper +PyObject* BoundBoxPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { // create a new instance of BoundBoxPy and the Twin object return new BoundBoxPy(new BoundBox3d); @@ -59,8 +59,14 @@ int BoundBoxPy::PyInit(PyObject* args, PyObject* /*kwd*/) } PyErr_Clear(); // set by PyArg_ParseTuple() - double xMin = 0.0, yMin = 0.0, zMin = 0.0, xMax = 0.0, yMax = 0.0, zMax = 0.0; - PyObject *object1 {}, *object2 {}; + double xMin = 0.0; + double yMin = 0.0; + double zMin = 0.0; + double xMax = 0.0; + double yMax = 0.0; + double zMax = 0.0; + PyObject* object1 {}; + PyObject* object2 {}; BoundBoxPy::PointerType ptr = getBoundBoxPtr(); if (PyArg_ParseTuple(args, "d|ddddd", &xMin, &yMin, &zMin, &xMax, &yMax, &zMax)) { ptr->MaxX = xMax; @@ -128,7 +134,9 @@ PyObject* BoundBoxPy::isValid(PyObject* args) PyObject* BoundBoxPy::add(PyObject* args) { - double x {}, y {}, z {}; + double x {}; + double y {}; + double z {}; PyObject* object {}; if (PyArg_ParseTuple(args, "ddd", &x, &y, &z)) { getBoundBoxPtr()->Add(Vector3d(x, y, z)); @@ -189,7 +197,8 @@ PyObject* BoundBoxPy::getEdge(PyObject* args) return nullptr; } - Base::Vector3d pnt1, pnt2; + Base::Vector3d pnt1; + Base::Vector3d pnt2; getBoundBoxPtr()->CalcEdge(index, pnt1, pnt2); Py::Tuple tuple(2); tuple.setItem(0, Py::Vector(pnt1)); @@ -199,7 +208,9 @@ PyObject* BoundBoxPy::getEdge(PyObject* args) PyObject* BoundBoxPy::closestPoint(PyObject* args) { - double x {}, y {}, z {}; + double x {}; + double y {}; + double z {}; PyObject* object {}; Base::Vector3d vec; @@ -221,10 +232,9 @@ PyObject* BoundBoxPy::closestPoint(PyObject* args) vec = *(static_cast(object)->getVectorPtr()); break; } - else { - PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); - return nullptr; - } + + PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); + return nullptr; } while (false); Base::Vector3d point = getBoundBoxPtr()->ClosestPoint(vec); @@ -233,7 +243,8 @@ PyObject* BoundBoxPy::closestPoint(PyObject* args) PyObject* BoundBoxPy::intersect(PyObject* args) { - PyObject *object {}, *object2 {}; + PyObject* object1 {}; + PyObject* object2 {}; Py::Boolean retVal; if (!getBoundBoxPtr()->IsValid()) { @@ -245,23 +256,23 @@ PyObject* BoundBoxPy::intersect(PyObject* args) if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), - &object, + &object1, &(Base::VectorPy::Type), &object2)) { retVal = getBoundBoxPtr()->IsCutLine( - *(static_cast(object)->getVectorPtr()), + *(static_cast(object1)->getVectorPtr()), *(static_cast(object2)->getVectorPtr())); break; } PyErr_Clear(); - if (PyArg_ParseTuple(args, "O!", &(Base::BoundBoxPy::Type), &object)) { - if (!static_cast(object)->getBoundBoxPtr()->IsValid()) { + if (PyArg_ParseTuple(args, "O!", &(Base::BoundBoxPy::Type), &object1)) { + if (!static_cast(object1)->getBoundBoxPtr()->IsValid()) { PyErr_SetString(PyExc_FloatingPointError, "Invalid bounding box argument"); return nullptr; } retVal = getBoundBoxPtr()->Intersect( - *(static_cast(object)->getBoundBoxPtr())); + *(static_cast(object1)->getBoundBoxPtr())); break; } @@ -326,12 +337,13 @@ PyObject* BoundBoxPy::enlarge(PyObject* args) PyObject* BoundBoxPy::getIntersectionPoint(PyObject* args) { - PyObject *object {}, *object2 {}; + PyObject* object1 {}; + PyObject* object2 {}; double epsilon = 0.0001; if (!PyArg_ParseTuple(args, "O!O!|d;Need base and direction vector", &(Base::VectorPy::Type), - &object, + &object1, &(Base::VectorPy::Type), &object2, &epsilon)) { @@ -340,22 +352,23 @@ PyObject* BoundBoxPy::getIntersectionPoint(PyObject* args) Base::Vector3d point; bool ok = getBoundBoxPtr()->IntersectionPoint( - *(static_cast(object)->getVectorPtr()), + *(static_cast(object1)->getVectorPtr()), *(static_cast(object2)->getVectorPtr()), point, epsilon); if (ok) { return new VectorPy(point); } - else { - PyErr_SetString(Base::PyExc_FC_GeneralError, "No intersection"); - return nullptr; - } + + PyErr_SetString(Base::PyExc_FC_GeneralError, "No intersection"); + return nullptr; } PyObject* BoundBoxPy::move(PyObject* args) { - double x {}, y {}, z {}; + double x {}; + double y {}; + double z {}; PyObject* object {}; Base::Vector3d vec; @@ -377,10 +390,9 @@ PyObject* BoundBoxPy::move(PyObject* args) vec = *(static_cast(object)->getVectorPtr()); break; } - else { - PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); - return nullptr; - } + + PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); + return nullptr; } while (false); getBoundBoxPtr()->MoveX(vec.x); @@ -392,7 +404,9 @@ PyObject* BoundBoxPy::move(PyObject* args) PyObject* BoundBoxPy::scale(PyObject* args) { - double x {}, y {}, z {}; + double x {}; + double y {}; + double z {}; PyObject* object {}; Base::Vector3d vec; @@ -414,10 +428,9 @@ PyObject* BoundBoxPy::scale(PyObject* args) vec = *(static_cast(object)->getVectorPtr()); break; } - else { - PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); - return nullptr; - } + + PyErr_SetString(PyExc_TypeError, "Either three floats or vector expected"); + return nullptr; } while (false); getBoundBoxPtr()->ScaleX(vec.x); @@ -445,7 +458,8 @@ PyObject* BoundBoxPy::transformed(PyObject* args) PyObject* BoundBoxPy::isCutPlane(PyObject* args) { - PyObject *object {}, *object2 {}; + PyObject* object {}; + PyObject* object2 {}; Py::Boolean retVal; if (!getBoundBoxPtr()->IsValid()) { @@ -470,7 +484,9 @@ PyObject* BoundBoxPy::isCutPlane(PyObject* args) PyObject* BoundBoxPy::isInside(PyObject* args) { - double x {}, y {}, z {}; + double x {}; + double y {}; + double z {}; PyObject* object {}; Py::Boolean retVal; diff --git a/src/Base/Builder3D.cpp b/src/Base/Builder3D.cpp index 73876446f5..d840ecc7c2 100644 --- a/src/Base/Builder3D.cpp +++ b/src/Base/Builder3D.cpp @@ -456,9 +456,9 @@ void ArrowItem::write(InventorOutput& out) const dir.Scale(sf2, sf2, sf2); Vector3f cpt = line.p1 + dir; - Vector3f rot = Vector3f(0.0f, 1.0f, 0.0f) % dir; + Vector3f rot = Vector3f(0.0F, 1.0F, 0.0F) % dir; rot.Normalize(); - float angle = Vector3f(0.0f, 1.0f, 0.0f).GetAngle(dir); + float angle = Vector3f(0.0F, 1.0F, 0.0F).GetAngle(dir); out.write() << "Separator {\n"; out.write() << " Material { diffuseColor " << rgb.red() << " " << rgb.green() << " " @@ -941,8 +941,8 @@ void TransformItem::write(InventorOutput& out) const // ----------------------------------------------------------------------------- -InventorBuilder::InventorBuilder(std::ostream& output) - : result(output) +InventorBuilder::InventorBuilder(std::ostream& str) + : result(str) { addHeader(); } @@ -1020,7 +1020,7 @@ void Builder3D::saveToLog() ILogger* obs = Base::Console().Get("StatusBar"); if (obs) { obs->SendLog("Builder3D", - result.str().c_str(), + result.str(), Base::LogStyle::Log, Base::IntendedRecipient::Developer, Base::ContentType::Untranslatable); @@ -1073,7 +1073,7 @@ std::vector InventorLoader::readData(const char* fieldName) const bool found = false; while (std::getline(inp, str)) { std::string::size_type point = str.find(fieldName); - std::string::size_type open = str.find("["); + std::string::size_type open = str.find('['); if (point != std::string::npos && open > point) { str = str.substr(open); found = true; @@ -1101,7 +1101,7 @@ std::vector InventorLoader::readData(const char* fieldName) const } // search for ']' to finish the reading - if (str.find("]") != std::string::npos) { + if (str.find(']') != std::string::npos) { break; } } while (std::getline(inp, str)); @@ -1240,25 +1240,22 @@ bool InventorLoader::read() bool InventorLoader::isValid() const { int32_t value {static_cast(points.size())}; - auto inRange = [value](const Face& f) { - if (f.p1 < 0 || f.p1 >= value) { + auto inRange = [value](const Face& face) { + if (face.p1 < 0 || face.p1 >= value) { return false; } - if (f.p2 < 0 || f.p2 >= value) { + if (face.p2 < 0 || face.p2 >= value) { return false; } - if (f.p3 < 0 || f.p3 >= value) { + if (face.p3 < 0 || face.p3 >= value) { return false; } return true; }; - for (auto it : faces) { - if (!inRange(it)) { - return false; - } - } - return true; + return std::all_of(faces.cbegin(), faces.cend(), [&inRange](const Face& face) { + return inRange(face); + }); } namespace Base diff --git a/src/Base/Builder3D.h b/src/Base/Builder3D.h index d23ca95241..b01d816f4d 100644 --- a/src/Base/Builder3D.h +++ b/src/Base/Builder3D.h @@ -208,13 +208,13 @@ public: { spaces -= 2; } - int count() + int count() const { return spaces; } - friend std::ostream& operator<<(std::ostream& os, Indentation m) + friend std::ostream& operator<<(std::ostream& os, Indentation ind) { - for (int i = 0; i < m.count(); i++) { + for (int i = 0; i < ind.count(); i++) { os << " "; } return os; diff --git a/src/Base/Console.cpp b/src/Base/Console.cpp index c161c25244..450864855a 100644 --- a/src/Base/Console.cpp +++ b/src/Base/Console.cpp @@ -68,7 +68,6 @@ public: , notifier(notifier) , msg(msg) {} - ~ConsoleEvent() override = default; }; class ConsoleOutput: public QObject // clazy:exclude=missing-qobject-macro @@ -139,13 +138,10 @@ public: } private: - ConsoleOutput() = default; - ~ConsoleOutput() override = default; - - static ConsoleOutput* instance; + static ConsoleOutput* instance; // NOLINT }; -ConsoleOutput* ConsoleOutput::instance = nullptr; +ConsoleOutput* ConsoleOutput::instance = nullptr; // NOLINT } // namespace Base @@ -176,9 +172,9 @@ ConsoleSingleton::~ConsoleSingleton() /** * sets the console in a special mode */ -void ConsoleSingleton::SetConsoleMode(ConsoleMode m) +void ConsoleSingleton::SetConsoleMode(ConsoleMode mode) { - if (m & Verbose) { + if (mode & Verbose) { _bVerbose = true; } } @@ -186,9 +182,9 @@ void ConsoleSingleton::SetConsoleMode(ConsoleMode m) /** * unsets the console from a special mode */ -void ConsoleSingleton::UnsetConsoleMode(ConsoleMode m) +void ConsoleSingleton::UnsetConsoleMode(ConsoleMode mode) { - if (m & Verbose) { + if (mode & Verbose) { _bVerbose = false; } } @@ -211,54 +207,53 @@ void ConsoleSingleton::UnsetConsoleMode(ConsoleMode m) * switches off warnings and error messages and restore the state before the modification. * If the observer \a sObs doesn't exist then nothing happens. */ -ConsoleMsgFlags ConsoleSingleton::SetEnabledMsgType(const char* sObs, ConsoleMsgFlags type, bool b) +ConsoleMsgFlags ConsoleSingleton::SetEnabledMsgType(const char* sObs, ConsoleMsgFlags type, bool on) { ILogger* pObs = Get(sObs); if (pObs) { ConsoleMsgFlags flags = 0; if (type & MsgType_Err) { - if (pObs->bErr != b) { + if (pObs->bErr != on) { flags |= MsgType_Err; } - pObs->bErr = b; + pObs->bErr = on; } if (type & MsgType_Wrn) { - if (pObs->bWrn != b) { + if (pObs->bWrn != on) { flags |= MsgType_Wrn; } - pObs->bWrn = b; + pObs->bWrn = on; } if (type & MsgType_Txt) { - if (pObs->bMsg != b) { + if (pObs->bMsg != on) { flags |= MsgType_Txt; } - pObs->bMsg = b; + pObs->bMsg = on; } if (type & MsgType_Log) { - if (pObs->bLog != b) { + if (pObs->bLog != on) { flags |= MsgType_Log; } - pObs->bLog = b; + pObs->bLog = on; } if (type & MsgType_Critical) { - if (pObs->bCritical != b) { + if (pObs->bCritical != on) { flags |= MsgType_Critical; } - pObs->bCritical = b; + pObs->bCritical = on; } if (type & MsgType_Notification) { - if (pObs->bNotification != b) { + if (pObs->bNotification != on) { flags |= MsgType_Notification; } - pObs->bNotification = b; + pObs->bNotification = on; } return flags; } - else { - return 0; - } + + return 0; } bool ConsoleSingleton::IsMsgTypeEnabled(const char* sObs, FreeCAD_ConsoleMsgType type) const @@ -814,9 +809,8 @@ PyObject* ConsoleSingleton::sPySetStatus(PyObject* /*self*/, PyObject* args) Py_Return; } - else { - Py_Error(Base::PyExc_FC_GeneralError, "Unknown logger type"); - } + + Py_Error(Base::PyExc_FC_GeneralError, "Unknown logger type"); } PY_CATCH; } diff --git a/src/Base/Console.h b/src/Base/Console.h index 45fb9c9443..ab2a2b3616 100644 --- a/src/Base/Console.h +++ b/src/Base/Console.h @@ -341,6 +341,7 @@ using PyMethodDef = struct PyMethodDef; * */ +// NOLINTBEGIN(bugprone-reserved-identifier,bugprone-macro-parentheses,cppcoreguidelines-macro-usage) #define FC_LOGLEVEL_DEFAULT -1 #define FC_LOGLEVEL_ERR 0 #define FC_LOGLEVEL_WARN 1 @@ -479,6 +480,7 @@ using PyMethodDef = struct PyMethodDef; } while (0) #endif // FC_LOG_NO_TIMING +// NOLINTEND(bugprone-reserved-identifier,bugprone-macro-parentheses,cppcoreguidelines-macro-usage) // TODO: Get rid of this typedef using ConsoleMsgFlags = unsigned int; @@ -487,12 +489,12 @@ namespace Base { #ifndef FC_LOG_NO_TIMING -inline FC_DURATION GetDuration(FC_TIME_POINT& t) +inline FC_DURATION GetDuration(FC_TIME_POINT& tp) { auto tnow = std::chrono::FC_TIME_CLOCK::now(); - auto d = std::chrono::duration_cast(tnow - t); - t = tnow; - return d; + auto dc = std::chrono::duration_cast(tnow - tp); + tp = tnow; + return dc; } #endif @@ -548,6 +550,10 @@ class BaseExport ILogger { public: ILogger() = default; + ILogger(const ILogger&) = delete; + ILogger(ILogger&&) = delete; + ILogger& operator=(const ILogger&) = delete; + ILogger& operator=(ILogger&&) = delete; virtual ~ILogger() = 0; /** Used to send a Log message at the given level. @@ -571,24 +577,24 @@ public: /** * Returns whether a LogStyle category is active or not */ - bool isActive(Base::LogStyle category) + bool isActive(Base::LogStyle category) const { if (category == Base::LogStyle::Log) { return bLog; } - else if (category == Base::LogStyle::Warning) { + if (category == Base::LogStyle::Warning) { return bWrn; } - else if (category == Base::LogStyle::Error) { + if (category == Base::LogStyle::Error) { return bErr; } - else if (category == Base::LogStyle::Message) { + if (category == Base::LogStyle::Message) { return bMsg; } - else if (category == Base::LogStyle::Critical) { + if (category == Base::LogStyle::Critical) { return bCritical; } - else if (category == Base::LogStyle::Notification) { + if (category == Base::LogStyle::Notification) { return bNotification; } @@ -805,11 +811,11 @@ public: }; /// Change mode - void SetConsoleMode(ConsoleMode m); + void SetConsoleMode(ConsoleMode mode); /// Change mode - void UnsetConsoleMode(ConsoleMode m); + void UnsetConsoleMode(ConsoleMode mode); /// Enables or disables message types of a certain console observer - ConsoleMsgFlags SetEnabledMsgType(const char* sObs, ConsoleMsgFlags type, bool b); + ConsoleMsgFlags SetEnabledMsgType(const char* sObs, ConsoleMsgFlags type, bool on); /// Checks if message types of a certain console observer are enabled bool IsMsgTypeEnabled(const char* sObs, FreeCAD_ConsoleMsgType type) const; void SetConnectionMode(ConnectionMode mode); @@ -839,7 +845,7 @@ public: inline constexpr FreeCAD_ConsoleMsgType getConsoleMsg(Base::LogStyle style); -protected: +private: // python exports goes here +++++++++++++++++++++++++++++++++++++++++++ // static python wrapper of the exported functions static PyObject* sPyLog(PyObject* self, PyObject* args); @@ -865,7 +871,13 @@ protected: // Singleton! ConsoleSingleton(); - virtual ~ConsoleSingleton(); + ~ConsoleSingleton(); + +public: + ConsoleSingleton(const ConsoleSingleton&) = delete; + ConsoleSingleton(ConsoleSingleton&&) = delete; + ConsoleSingleton& operator=(const ConsoleSingleton&) = delete; + ConsoleSingleton& operator=(ConsoleSingleton&&) = delete; private: void postEvent(ConsoleSingleton::FreeCAD_ConsoleMsgType type, @@ -881,7 +893,7 @@ private: // singleton static void Destruct(); - static ConsoleSingleton* _pcSingleton; + static ConsoleSingleton* _pcSingleton; // NOLINT // observer list std::set _aclObservers; @@ -927,6 +939,11 @@ public: { Console().EnableRefresh(true); } + + ConsoleRefreshDisabler(const ConsoleRefreshDisabler&) = delete; + ConsoleRefreshDisabler(ConsoleRefreshDisabler&&) = delete; + ConsoleRefreshDisabler& operator=(const ConsoleRefreshDisabler&) = delete; + ConsoleRefreshDisabler& operator=(ConsoleRefreshDisabler&&) = delete; }; @@ -957,9 +974,9 @@ public: , refresh(refresh) {} - bool isEnabled(int l) + bool isEnabled(int lev) const { - return l <= level(); + return lev <= level(); } int level() const diff --git a/src/Base/ConsoleObserver.cpp b/src/Base/ConsoleObserver.cpp index 7ad627a239..1fd0ae5ead 100644 --- a/src/Base/ConsoleObserver.cpp +++ b/src/Base/ConsoleObserver.cpp @@ -197,7 +197,7 @@ void ConsoleObserverStd::Error(const char* sErr) } } -void ConsoleObserverStd::Log(const char* sErr) +void ConsoleObserverStd::Log(const char* sLog) { if (useColorStderr) { #if defined(FC_OS_WIN32) @@ -208,7 +208,7 @@ void ConsoleObserverStd::Log(const char* sErr) #endif } - fprintf(stderr, "%s", sErr); + fprintf(stderr, "%s", sLog); if (useColorStderr) { #if defined(FC_OS_WIN32) @@ -248,12 +248,12 @@ RedirectStdOutput::RedirectStdOutput() buffer.reserve(80); } -int RedirectStdOutput::overflow(int c) +int RedirectStdOutput::overflow(int ch) { - if (c != EOF) { - buffer.push_back(static_cast(c)); + if (ch != EOF) { + buffer.push_back(static_cast(ch)); } - return c; + return ch; } int RedirectStdOutput::sync() @@ -271,12 +271,12 @@ RedirectStdLog::RedirectStdLog() buffer.reserve(80); } -int RedirectStdLog::overflow(int c) +int RedirectStdLog::overflow(int ch) { - if (c != EOF) { - buffer.push_back(static_cast(c)); + if (ch != EOF) { + buffer.push_back(static_cast(ch)); } - return c; + return ch; } int RedirectStdLog::sync() @@ -294,12 +294,12 @@ RedirectStdError::RedirectStdError() buffer.reserve(80); } -int RedirectStdError::overflow(int c) +int RedirectStdError::overflow(int ch) { - if (c != EOF) { - buffer.push_back(static_cast(c)); + if (ch != EOF) { + buffer.push_back(static_cast(ch)); } - return c; + return ch; } int RedirectStdError::sync() @@ -323,8 +323,8 @@ std::stringstream& LogLevel::prefix(std::stringstream& str, const char* src, int _FC_TIME_INIT(s_tstart); } auto tnow = std::chrono::FC_TIME_CLOCK::now(); - auto d = std::chrono::duration_cast(tnow - s_tstart); - str << d.count() << ' '; + auto dc = std::chrono::duration_cast(tnow - s_tstart); + str << dc.count() << ' '; } if (print_tag) { str << '<' << tag << "> "; diff --git a/src/Base/ConsoleObserver.h b/src/Base/ConsoleObserver.h index 74e9f45a27..e3c23a04c9 100644 --- a/src/Base/ConsoleObserver.h +++ b/src/Base/ConsoleObserver.h @@ -132,14 +132,19 @@ ILoggerBlocker::ILoggerBlocker(const char* co, ConsoleMsgFlags msgTypes) ILoggerBlocker::~ILoggerBlocker() { + try { #ifdef FC_DEBUG - auto debug = Console().SetEnabledMsgType(conObs, msgTypesBlocked, true); - if (debug != msgTypesBlocked) { - Console().Warning("Enabled message types have been changed while ILoggerBlocker was set\n"); - } + auto debug = Console().SetEnabledMsgType(conObs, msgTypesBlocked, true); + if (debug != msgTypesBlocked) { + Console().Warning( + "Enabled message types have been changed while ILoggerBlocker was set\n"); + } #else - Console().SetEnabledMsgType(conObs, msgTypesBlocked, true); + Console().SetEnabledMsgType(conObs, msgTypesBlocked, true); #endif + } + catch (...) { + } } class BaseExport RedirectStdOutput: public std::streambuf @@ -148,7 +153,7 @@ public: RedirectStdOutput(); protected: - int overflow(int c = EOF) override; + int overflow(int ch = EOF) override; int sync() override; private: @@ -161,7 +166,7 @@ public: RedirectStdError(); protected: - int overflow(int c = EOF) override; + int overflow(int ch = EOF) override; int sync() override; private: @@ -174,7 +179,7 @@ public: RedirectStdLog(); protected: - int overflow(int c = EOF) override; + int overflow(int ch = EOF) override; int sync() override; private: diff --git a/src/Base/Converter.h b/src/Base/Converter.h index 2a7aa40a81..a524fd67a4 100644 --- a/src/Base/Converter.h +++ b/src/Base/Converter.h @@ -42,8 +42,8 @@ struct vec_traits { using vec_type = Vector3f; using float_type = float; - vec_traits(const vec_type& v) - : v(v) + explicit vec_traits(const vec_type& vec) + : v(vec) {} inline std::tuple get() const { @@ -59,8 +59,8 @@ struct vec_traits { using vec_type = Vector3d; using float_type = double; - vec_traits(const vec_type& v) - : v(v) + explicit vec_traits(const vec_type& vec) + : v(vec) {} inline std::tuple get() const { @@ -76,12 +76,15 @@ struct vec_traits { using vec_type = Rotation; using float_type = double; - vec_traits(const vec_type& v) - : v(v) + explicit vec_traits(const vec_type& vec) + : v(vec) {} inline std::tuple get() const { - float_type q1 {}, q2 {}, q3 {}, q4 {}; + float_type q1 {}; + float_type q2 {}; + float_type q3 {}; + float_type q4 {}; v.getValue(q1, q2, q3, q4); return std::make_tuple(q1, q2, q3, q4); } @@ -91,36 +94,36 @@ private: }; // type with three floats -template -_Vec make_vec(const std::tuple&& t) +template +Vec make_vec(const std::tuple&& ft) { - using traits_type = vec_traits<_Vec>; + using traits_type = vec_traits; using float_traits_type = typename traits_type::float_type; - return _Vec(float_traits_type(std::get<0>(t)), - float_traits_type(std::get<1>(t)), - float_traits_type(std::get<2>(t))); + return Vec(float_traits_type(std::get<0>(ft)), + float_traits_type(std::get<1>(ft)), + float_traits_type(std::get<2>(ft))); } // type with four floats -template -_Vec make_vec(const std::tuple&& t) +template +Vec make_vec(const std::tuple&& ft) { - using traits_type = vec_traits<_Vec>; + using traits_type = vec_traits; using float_traits_type = typename traits_type::float_type; - return _Vec(float_traits_type(std::get<0>(t)), - float_traits_type(std::get<1>(t)), - float_traits_type(std::get<2>(t)), - float_traits_type(std::get<3>(t))); + return Vec(float_traits_type(std::get<0>(ft)), + float_traits_type(std::get<1>(ft)), + float_traits_type(std::get<2>(ft)), + float_traits_type(std::get<3>(ft))); } -template -inline _Vec1 convertTo(const _Vec2& v) +template +inline Vec1 convertTo(const Vec2& vec) { - using traits_type = vec_traits<_Vec2>; + using traits_type = vec_traits; using float_type = typename traits_type::float_type; - traits_type t(v); - auto tuple = t.get(); - return make_vec<_Vec1, float_type>(std::move(tuple)); + traits_type tt(vec); + auto tuple = tt.get(); + return make_vec(std::move(tuple)); } } // namespace Base diff --git a/src/Base/CoordinateSystem.cpp b/src/Base/CoordinateSystem.cpp index 40fe56b1e7..4134bed8f9 100644 --- a/src/Base/CoordinateSystem.cpp +++ b/src/Base/CoordinateSystem.cpp @@ -36,23 +36,21 @@ CoordinateSystem::CoordinateSystem() , ydir(0, 1, 0) {} -CoordinateSystem::~CoordinateSystem() = default; - -void CoordinateSystem::setAxes(const Axis& v, const Vector3d& xd) +void CoordinateSystem::setAxes(const Axis& vec, const Vector3d& xd) { if (xd.Sqr() < Base::Vector3d::epsilon()) { throw Base::ValueError("Direction is null vector"); } - Vector3d yd = v.getDirection() % xd; + Vector3d yd = vec.getDirection() % xd; if (yd.Sqr() < Base::Vector3d::epsilon()) { throw Base::ValueError("Direction is parallel to Z direction"); } ydir = yd; ydir.Normalize(); - xdir = ydir % v.getDirection(); + xdir = ydir % vec.getDirection(); xdir.Normalize(); - axis.setBase(v.getBase()); - Base::Vector3d zdir = v.getDirection(); + axis.setBase(vec.getBase()); + Base::Vector3d zdir = vec.getDirection(); zdir.Normalize(); axis.setDirection(zdir); } @@ -75,9 +73,9 @@ void CoordinateSystem::setAxes(const Vector3d& n, const Vector3d& xd) axis.setDirection(zdir); } -void CoordinateSystem::setAxis(const Axis& v) +void CoordinateSystem::setAxis(const Axis& axis) { - setAxes(v, xdir); + setAxes(axis, xdir); } void CoordinateSystem::setXDirection(const Vector3d& dir) @@ -111,6 +109,7 @@ void CoordinateSystem::setZDirection(const Vector3d& dir) Placement CoordinateSystem::displacement(const CoordinateSystem& cs) const { + // NOLINTBEGIN const Base::Vector3d& a = axis.getBase(); const Base::Vector3d& zdir = axis.getDirection(); Base::Matrix4D At; @@ -148,36 +147,37 @@ Placement CoordinateSystem::displacement(const CoordinateSystem& cs) const Placement PB(B); Placement C = PB * PAt; return C; + // NOLINTEND } -void CoordinateSystem::transformTo(Vector3d& p) +void CoordinateSystem::transformTo(Vector3d& pnt) { - return p.TransformToCoordinateSystem(axis.getBase(), xdir, ydir); + return pnt.TransformToCoordinateSystem(axis.getBase(), xdir, ydir); } -void CoordinateSystem::transform(const Placement& p) +void CoordinateSystem::transform(const Placement& plm) { - axis *= p; - p.getRotation().multVec(this->xdir, this->xdir); - p.getRotation().multVec(this->ydir, this->ydir); + axis *= plm; + plm.getRotation().multVec(this->xdir, this->xdir); + plm.getRotation().multVec(this->ydir, this->ydir); } -void CoordinateSystem::transform(const Rotation& r) +void CoordinateSystem::transform(const Rotation& rot) { Vector3d zdir = axis.getDirection(); - r.multVec(zdir, zdir); + rot.multVec(zdir, zdir); axis.setDirection(zdir); - r.multVec(this->xdir, this->xdir); - r.multVec(this->ydir, this->ydir); + rot.multVec(this->xdir, this->xdir); + rot.multVec(this->ydir, this->ydir); } -void CoordinateSystem::setPlacement(const Placement& p) +void CoordinateSystem::setPlacement(const Placement& plm) { Vector3d zdir(0, 0, 1); - p.getRotation().multVec(zdir, zdir); - axis.setBase(p.getPosition()); + plm.getRotation().multVec(zdir, zdir); + axis.setBase(plm.getPosition()); axis.setDirection(zdir); - p.getRotation().multVec(Vector3d(1, 0, 0), this->xdir); - p.getRotation().multVec(Vector3d(0, 1, 0), this->ydir); + plm.getRotation().multVec(Vector3d(1, 0, 0), this->xdir); + plm.getRotation().multVec(Vector3d(0, 1, 0), this->ydir); } diff --git a/src/Base/CoordinateSystem.h b/src/Base/CoordinateSystem.h index 1757a47f14..f38bb016be 100644 --- a/src/Base/CoordinateSystem.h +++ b/src/Base/CoordinateSystem.h @@ -41,7 +41,7 @@ public: CoordinateSystem(); CoordinateSystem(const CoordinateSystem&) = default; CoordinateSystem(CoordinateSystem&&) = default; - ~CoordinateSystem(); + ~CoordinateSystem() = default; CoordinateSystem& operator=(const CoordinateSystem&) = default; CoordinateSystem& operator=(CoordinateSystem&&) = default; @@ -49,7 +49,7 @@ public: /** Sets the main axis. X and Y dir are adjusted accordingly. * The main axis \a v must not be parallel to the X axis */ - void setAxis(const Axis& v); + void setAxis(const Axis& axis); /** Sets the main axis. X and Y dir are adjusted accordingly. * The main axis must not be parallel to \a xd */ @@ -85,9 +85,9 @@ public: { return axis.getDirection(); } - inline void setPosition(const Vector3d& p) + inline void setPosition(const Vector3d& pos) { - axis.setBase(p); + axis.setBase(pos); } inline const Vector3d& getPosition() const { @@ -99,17 +99,17 @@ public: */ Placement displacement(const CoordinateSystem& cs) const; - /** Transform the point \a p to be in this coordinate system */ - void transformTo(Vector3d& p); + /** Transform the point \a pnt to be in this coordinate system */ + void transformTo(Vector3d& pnt); - /** Apply the placement \a p to the coordinate system. */ - void transform(const Placement& p); + /** Apply the placement \a plm to the coordinate system. */ + void transform(const Placement& plm); - /** Apply the rotation \a r to the coordinate system. */ - void transform(const Rotation& r); + /** Apply the rotation \a rot to the coordinate system. */ + void transform(const Rotation& rot); - /** Set the placement \a p to the coordinate system. */ - void setPlacement(const Placement& p); + /** Set the placement \a plm to the coordinate system. */ + void setPlacement(const Placement& plm); private: Axis axis; diff --git a/src/Base/CoordinateSystemPyImp.cpp b/src/Base/CoordinateSystemPyImp.cpp index 82cb6a53ba..a0cf08d323 100644 --- a/src/Base/CoordinateSystemPyImp.cpp +++ b/src/Base/CoordinateSystemPyImp.cpp @@ -38,7 +38,8 @@ std::string CoordinateSystemPy::representation() const return {""}; } -PyObject* CoordinateSystemPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper +PyObject* +CoordinateSystemPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { // create a new instance of CoordinateSystemPy and the Twin object return new CoordinateSystemPy(new CoordinateSystem); @@ -52,7 +53,8 @@ int CoordinateSystemPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) PyObject* CoordinateSystemPy::setAxes(PyObject* args) { - PyObject *axis {}, *xdir {}; + PyObject* axis {}; + PyObject* xdir {}; if (PyArg_ParseTuple(args, "O!O!", &(AxisPy::Type), &axis, &(VectorPy::Type), &xdir)) { getCoordinateSystemPtr()->setAxes(*static_cast(axis)->getAxisPtr(), *static_cast(xdir)->getVectorPtr()); @@ -76,20 +78,20 @@ PyObject* CoordinateSystemPy::displacement(PyObject* args) if (!PyArg_ParseTuple(args, "O!", &(CoordinateSystemPy::Type), &cs)) { return nullptr; } - Placement p = getCoordinateSystemPtr()->displacement( + Placement plm = getCoordinateSystemPtr()->displacement( *static_cast(cs)->getCoordinateSystemPtr()); - return new PlacementPy(new Placement(p)); + return new PlacementPy(new Placement(plm)); } PyObject* CoordinateSystemPy::transformTo(PyObject* args) { - PyObject* vec {}; - if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &vec)) { + PyObject* vecpy {}; + if (!PyArg_ParseTuple(args, "O!", &(VectorPy::Type), &vecpy)) { return nullptr; } - Vector3d v = static_cast(vec)->value(); - getCoordinateSystemPtr()->transformTo(v); - return new VectorPy(new Vector3d(v)); + Vector3d vec = static_cast(vecpy)->value(); + getCoordinateSystemPtr()->transformTo(vec); + return new VectorPy(new Vector3d(vec)); } PyObject* CoordinateSystemPy::transform(PyObject* args) diff --git a/src/Base/Debugger.cpp b/src/Base/Debugger.cpp index 94c6d9c9c6..302b4f9311 100644 --- a/src/Base/Debugger.cpp +++ b/src/Base/Debugger.cpp @@ -51,7 +51,7 @@ void Debugger::detach() isAttached = false; } -bool Debugger::eventFilter(QObject*, QEvent* event) +bool Debugger::eventFilter(QObject* /*watched*/, QEvent* event) { if (event->type() == QEvent::KeyPress) { if (loop.isRunning()) { diff --git a/src/Base/DualNumber.h b/src/Base/DualNumber.h index 32bd6efa8a..0b5224a998 100644 --- a/src/Base/DualNumber.h +++ b/src/Base/DualNumber.h @@ -25,6 +25,7 @@ #include +// NOLINTBEGIN(readability-identifier-length) namespace Base { @@ -44,7 +45,7 @@ public: public: DualNumber() = default; - DualNumber(double re, double du = 0.0) + DualNumber(double re, double du = 0.0) // NOLINT : re(re) , du(du) {} @@ -107,6 +108,7 @@ inline DualNumber pow(DualNumber a, double pw) return {std::pow(a.re, pw), pw * std::pow(a.re, pw - 1.0) * a.du}; } } // namespace Base +// NOLINTEND(readability-identifier-length) #endif diff --git a/src/Base/DualQuaternion.cpp b/src/Base/DualQuaternion.cpp index 2dc144ad9d..e1b611e882 100644 --- a/src/Base/DualQuaternion.cpp +++ b/src/Base/DualQuaternion.cpp @@ -26,6 +26,7 @@ #include "DualQuaternion.h" +// NOLINTBEGIN(readability-identifier-length) Base::DualQuat Base::operator+(Base::DualQuat a, Base::DualQuat b) { return {a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w}; @@ -131,3 +132,4 @@ Base::DualQuat Base::DualQuat::pow(double t, bool shorten) const m * sin(theta / 2) + pitch / 2 * cos(theta / 2) * l + DualQuat(0, 0, 0, -pitch / 2 * sin(theta / 2))}; } +// NOLINTEND(readability-identifier-length) diff --git a/src/Base/DualQuaternion.h b/src/Base/DualQuaternion.h index 467c205b17..cef6394663 100644 --- a/src/Base/DualQuaternion.h +++ b/src/Base/DualQuaternion.h @@ -26,7 +26,7 @@ #include "DualNumber.h" #include - +// NOLINTBEGIN(readability-identifier-length) namespace Base { @@ -146,5 +146,6 @@ BaseExport DualQuat operator*(DualNumber a, DualQuat b); } // namespace Base +// NOLINTEND(readability-identifier-length) #endif diff --git a/src/Base/Exception.cpp b/src/Base/Exception.cpp index 168380d8e9..c2e419a73f 100644 --- a/src/Base/Exception.cpp +++ b/src/Base/Exception.cpp @@ -47,6 +47,8 @@ Exception::Exception() Exception::Exception(const Exception& inst) = default; +Exception::Exception(Exception&& inst) noexcept = default; + Exception::Exception(const char* sMessage) : _sErrMsg(sMessage) , _line(0) @@ -67,6 +69,17 @@ Exception& Exception::operator=(const Exception& inst) _file = inst._file; _line = inst._line; _function = inst._function; + _isTranslatable = inst._isTranslatable; + return *this; +} + +Exception& Exception::operator=(Exception&& inst) noexcept +{ + _sErrMsg = std::move(inst._sErrMsg); + _file = std::move(inst._file); + _line = inst._line; + _function = std::move(inst._function); + _isTranslatable = inst._isTranslatable; return *this; } @@ -86,12 +99,14 @@ void Exception::ReportException() const msg = _sErrMsg.c_str(); } #ifdef FC_DEBUG - if (_function.size()) { + if (!_function.empty()) { _FC_ERR(_file.c_str(), _line, _function << " -- " << msg); } else #endif + { _FC_ERR(_file.c_str(), _line, msg); + } _isReported = true; } } @@ -184,9 +199,7 @@ PyObject* AbortException::getPyExceptionType() const // --------------------------------------------------------- -XMLBaseException::XMLBaseException() - : Exception() -{} +XMLBaseException::XMLBaseException() = default; XMLBaseException::XMLBaseException(const char* sMessage) : Exception(sMessage) @@ -289,14 +302,6 @@ std::string FileException::getFileName() const return file.fileName(); } -FileException& FileException::operator=(const FileException& inst) -{ - Exception::operator=(inst); - file = inst.file; - _sErrMsgAndFileName = inst._sErrMsgAndFileName; - return *this; -} - const char* FileException::what() const noexcept { return _sErrMsgAndFileName.c_str(); @@ -313,12 +318,14 @@ void FileException::ReportException() const msg = _sErrMsgAndFileName.c_str(); } #ifdef FC_DEBUG - if (_function.size()) { + if (!_function.empty()) { _FC_ERR(_file.c_str(), _line, _function << " -- " << msg); } else #endif + { _FC_ERR(_file.c_str(), _line, msg); + } _isReported = true; } } @@ -350,9 +357,7 @@ PyObject* FileException::getPyExceptionType() const // --------------------------------------------------------- -FileSystemError::FileSystemError() - : Exception() -{} +FileSystemError::FileSystemError() = default; FileSystemError::FileSystemError(const char* sMessage) : Exception(sMessage) @@ -370,9 +375,7 @@ PyObject* FileSystemError::getPyExceptionType() const // --------------------------------------------------------- -BadFormatError::BadFormatError() - : Exception() -{} +BadFormatError::BadFormatError() = default; BadFormatError::BadFormatError(const char* sMessage) : Exception(sMessage) @@ -404,12 +407,27 @@ MemoryException::MemoryException(const MemoryException& inst) #endif {} +MemoryException::MemoryException(MemoryException&& inst) noexcept +#if defined(__GNUC__) + : std::bad_alloc() + , Exception(inst) +#else + : Exception(inst) +#endif +{} + MemoryException& MemoryException::operator=(const MemoryException& inst) { Exception::operator=(inst); return *this; } +MemoryException& MemoryException::operator=(MemoryException&& inst) noexcept +{ + Exception::operator=(inst); + return *this; +} + #if defined(__GNUC__) const char* MemoryException::what() const noexcept { @@ -465,9 +483,7 @@ PyObject* AbnormalProgramTermination::getPyExceptionType() const // --------------------------------------------------------- -UnknownProgramOption::UnknownProgramOption() - : Exception() -{} +UnknownProgramOption::UnknownProgramOption() = default; UnknownProgramOption::UnknownProgramOption(const char* sMessage) : Exception(sMessage) @@ -484,9 +500,7 @@ PyObject* UnknownProgramOption::getPyExceptionType() const // --------------------------------------------------------- -ProgramInformation::ProgramInformation() - : Exception() -{} +ProgramInformation::ProgramInformation() = default; ProgramInformation::ProgramInformation(const char* sMessage) : Exception(sMessage) @@ -498,9 +512,7 @@ ProgramInformation::ProgramInformation(const std::string& sMessage) // --------------------------------------------------------- -TypeError::TypeError() - : Exception() -{} +TypeError::TypeError() = default; TypeError::TypeError(const char* sMessage) : Exception(sMessage) @@ -517,9 +529,7 @@ PyObject* TypeError::getPyExceptionType() const // --------------------------------------------------------- -ValueError::ValueError() - : Exception() -{} +ValueError::ValueError() = default; ValueError::ValueError(const char* sMessage) : Exception(sMessage) @@ -536,9 +546,7 @@ PyObject* ValueError::getPyExceptionType() const // --------------------------------------------------------- -IndexError::IndexError() - : Exception() -{} +IndexError::IndexError() = default; IndexError::IndexError(const char* sMessage) : Exception(sMessage) @@ -555,9 +563,7 @@ PyObject* IndexError::getPyExceptionType() const // --------------------------------------------------------- -NameError::NameError() - : Exception() -{} +NameError::NameError() = default; NameError::NameError(const char* sMessage) : Exception(sMessage) @@ -574,9 +580,7 @@ PyObject* NameError::getPyExceptionType() const // --------------------------------------------------------- -ImportError::ImportError() - : Exception() -{} +ImportError::ImportError() = default; ImportError::ImportError(const char* sMessage) : Exception(sMessage) @@ -593,9 +597,7 @@ PyObject* ImportError::getPyExceptionType() const // --------------------------------------------------------- -AttributeError::AttributeError() - : Exception() -{} +AttributeError::AttributeError() = default; AttributeError::AttributeError(const char* sMessage) : Exception(sMessage) @@ -612,9 +614,7 @@ PyObject* AttributeError::getPyExceptionType() const // --------------------------------------------------------- -RuntimeError::RuntimeError() - : Exception() -{} +RuntimeError::RuntimeError() = default; RuntimeError::RuntimeError(const char* sMessage) : Exception(sMessage) @@ -650,9 +650,7 @@ PyObject* BadGraphError::getPyExceptionType() const // --------------------------------------------------------- -NotImplementedError::NotImplementedError() - : Exception() -{} +NotImplementedError::NotImplementedError() = default; NotImplementedError::NotImplementedError(const char* sMessage) : Exception(sMessage) @@ -669,9 +667,7 @@ PyObject* NotImplementedError::getPyExceptionType() const // --------------------------------------------------------- -ZeroDivisionError::ZeroDivisionError() - : Exception() -{} +ZeroDivisionError::ZeroDivisionError() = default; ZeroDivisionError::ZeroDivisionError(const char* sMessage) : Exception(sMessage) @@ -688,9 +684,7 @@ PyObject* ZeroDivisionError::getPyExceptionType() const // --------------------------------------------------------- -ReferenceError::ReferenceError() - : Exception() -{} +ReferenceError::ReferenceError() = default; ReferenceError::ReferenceError(const char* sMessage) : Exception(sMessage) @@ -707,9 +701,7 @@ PyObject* ReferenceError::getPyExceptionType() const // --------------------------------------------------------- -ExpressionError::ExpressionError() - : Exception() -{} +ExpressionError::ExpressionError() = default; ExpressionError::ExpressionError(const char* sMessage) : Exception(sMessage) @@ -726,9 +718,7 @@ PyObject* ExpressionError::getPyExceptionType() const // --------------------------------------------------------- -ParserError::ParserError() - : Exception() -{} +ParserError::ParserError() = default; ParserError::ParserError(const char* sMessage) : Exception(sMessage) @@ -745,9 +735,7 @@ PyObject* ParserError::getPyExceptionType() const // --------------------------------------------------------- -UnicodeError::UnicodeError() - : Exception() -{} +UnicodeError::UnicodeError() = default; UnicodeError::UnicodeError(const char* sMessage) : Exception(sMessage) @@ -764,9 +752,7 @@ PyObject* UnicodeError::getPyExceptionType() const // --------------------------------------------------------- -OverflowError::OverflowError() - : Exception() -{} +OverflowError::OverflowError() = default; OverflowError::OverflowError(const char* sMessage) : Exception(sMessage) @@ -783,9 +769,7 @@ PyObject* OverflowError::getPyExceptionType() const // --------------------------------------------------------- -UnderflowError::UnderflowError() - : Exception() -{} +UnderflowError::UnderflowError() = default; UnderflowError::UnderflowError(const char* sMessage) : Exception(sMessage) @@ -802,9 +786,7 @@ PyObject* UnderflowError::getPyExceptionType() const // --------------------------------------------------------- -UnitsMismatchError::UnitsMismatchError() - : Exception() -{} +UnitsMismatchError::UnitsMismatchError() = default; UnitsMismatchError::UnitsMismatchError(const char* sMessage) : Exception(sMessage) @@ -821,9 +803,7 @@ PyObject* UnitsMismatchError::getPyExceptionType() const // --------------------------------------------------------- -CADKernelError::CADKernelError() - : Exception() -{} +CADKernelError::CADKernelError() = default; CADKernelError::CADKernelError(const char* sMessage) : Exception(sMessage) @@ -840,9 +820,7 @@ PyObject* CADKernelError::getPyExceptionType() const // --------------------------------------------------------- -RestoreError::RestoreError() - : Exception() -{} +RestoreError::RestoreError() = default; RestoreError::RestoreError(const char* sMessage) : Exception(sMessage) diff --git a/src/Base/Exception.h b/src/Base/Exception.h index c93bf7218b..6430ec0990 100644 --- a/src/Base/Exception.h +++ b/src/Base/Exception.h @@ -47,6 +47,7 @@ using PyObject = struct _object; /// have provided one) at that time it gets translated (e.g. in the UI before showing the message of /// the exception). +// NOLINTBEGIN #ifdef _MSC_VER #define THROW(exception) \ @@ -185,6 +186,7 @@ using PyObject = struct _object; ss << _msg; \ THROWM(_exception, ss.str().c_str()); \ } while (0) +// NOLINTEND namespace Base { @@ -197,6 +199,7 @@ public: ~Exception() noexcept override = default; Exception& operator=(const Exception& inst); + Exception& operator=(Exception&& inst) noexcept; virtual const char* what() const noexcept; @@ -219,8 +222,7 @@ public: /// setter methods for including debug information /// intended to use via macro for autofilling of debugging information - inline void - setDebugInformation(const std::string& file, const int line, const std::string& function); + inline void setDebugInformation(const std::string& file, int line, const std::string& function); inline void setTranslatable(bool translatable); @@ -249,6 +251,7 @@ protected: Exception(const std::string& sMessage); Exception(); Exception(const Exception& inst); + Exception(Exception&& inst) noexcept; protected: std::string _sErrMsg; @@ -273,9 +276,14 @@ public: AbortException(const char* sMessage); /// Construction AbortException(); + AbortException(const AbortException&) = default; + AbortException(AbortException&&) = default; /// Destruction ~AbortException() noexcept override = default; + AbortException& operator=(const AbortException&) = default; + AbortException& operator=(AbortException&&) = default; + /// Description of the exception const char* what() const noexcept override; /// returns the corresponding python exception type @@ -293,9 +301,14 @@ public: XMLBaseException(); XMLBaseException(const char* sMessage); XMLBaseException(const std::string& sMessage); + XMLBaseException(const XMLBaseException&) = default; + XMLBaseException(XMLBaseException&&) = default; /// Destruction ~XMLBaseException() noexcept override = default; + XMLBaseException& operator=(const XMLBaseException&) = default; + XMLBaseException& operator=(XMLBaseException&&) = default; + PyObject* getPyExceptionType() const override; }; @@ -312,9 +325,14 @@ public: XMLParseException(const std::string& sMessage); /// Construction XMLParseException(); + XMLParseException(const XMLParseException&) = default; + XMLParseException(XMLParseException&&) = default; /// Destruction ~XMLParseException() noexcept override = default; + XMLParseException& operator=(const XMLParseException&) = default; + XMLParseException& operator=(XMLParseException&&) = default; + /// Description of the exception const char* what() const noexcept override; PyObject* getPyExceptionType() const override; @@ -333,9 +351,14 @@ public: XMLAttributeError(const std::string& sMessage); /// Construction XMLAttributeError(); + XMLAttributeError(const XMLAttributeError&) = default; + XMLAttributeError(XMLAttributeError&&) = default; /// Destruction ~XMLAttributeError() noexcept override = default; + XMLAttributeError& operator=(const XMLAttributeError&) = default; + XMLAttributeError& operator=(XMLAttributeError&&) = default; + /// Description of the exception const char* what() const noexcept override; PyObject* getPyExceptionType() const override; @@ -354,12 +377,14 @@ public: FileException(const char* sMessage, const FileInfo& File); /// standard construction FileException(); - /// Construction FileException(const FileException&) = default; + FileException(FileException&&) = default; /// Destruction ~FileException() noexcept override = default; /// Assignment operator - FileException& operator=(const FileException& inst); + FileException& operator=(const FileException&) = default; + FileException& operator=(FileException&&) = default; + /// Description of the exception const char* what() const noexcept override; /// Report generation @@ -393,8 +418,13 @@ public: FileSystemError(); FileSystemError(const char* sMessage); FileSystemError(const std::string& sMessage); + FileSystemError(const FileSystemError&) = default; + FileSystemError(FileSystemError&&) = default; /// Destruction ~FileSystemError() noexcept override = default; + FileSystemError& operator=(const FileSystemError&) = default; + FileSystemError& operator=(FileSystemError&&) = default; + PyObject* getPyExceptionType() const override; }; @@ -409,8 +439,12 @@ public: BadFormatError(); BadFormatError(const char* sMessage); BadFormatError(const std::string& sMessage); + BadFormatError(const BadFormatError&) = default; + BadFormatError(BadFormatError&&) = default; /// Destruction ~BadFormatError() noexcept override = default; + BadFormatError& operator=(const BadFormatError&) = default; + BadFormatError& operator=(BadFormatError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -430,10 +464,12 @@ public: MemoryException(); /// Construction MemoryException(const MemoryException& inst); + MemoryException(MemoryException&& inst) noexcept; /// Destruction ~MemoryException() noexcept override = default; /// Assignment operator MemoryException& operator=(const MemoryException& inst); + MemoryException& operator=(MemoryException&& inst) noexcept; #if defined(__GNUC__) /// Description of the exception const char* what() const noexcept override; @@ -452,8 +488,12 @@ public: AccessViolation(); AccessViolation(const char* sMessage); AccessViolation(const std::string& sMessage); + AccessViolation(const AccessViolation&) = default; + AccessViolation(AccessViolation&&) = default; /// Destruction ~AccessViolation() noexcept override = default; + AccessViolation& operator=(const AccessViolation&) = default; + AccessViolation& operator=(AccessViolation&&) = default; PyObject* getPyExceptionType() const override; }; @@ -469,8 +509,12 @@ public: /// Construction AbnormalProgramTermination(const char* sMessage); AbnormalProgramTermination(const std::string& sMessage); + AbnormalProgramTermination(const AbnormalProgramTermination&) = default; + AbnormalProgramTermination(AbnormalProgramTermination&&) = default; /// Destruction ~AbnormalProgramTermination() noexcept override = default; + AbnormalProgramTermination& operator=(const AbnormalProgramTermination&) = default; + AbnormalProgramTermination& operator=(AbnormalProgramTermination&&) = default; PyObject* getPyExceptionType() const override; }; @@ -485,8 +529,12 @@ public: UnknownProgramOption(); UnknownProgramOption(const char* sMessage); UnknownProgramOption(const std::string& sMessage); + UnknownProgramOption(const UnknownProgramOption&) = default; + UnknownProgramOption(UnknownProgramOption&&) = default; /// Destruction ~UnknownProgramOption() noexcept override = default; + UnknownProgramOption& operator=(const UnknownProgramOption&) = default; + UnknownProgramOption& operator=(UnknownProgramOption&&) = default; PyObject* getPyExceptionType() const override; }; @@ -501,9 +549,13 @@ public: ProgramInformation(); ProgramInformation(const char* sMessage); ProgramInformation(const std::string& sMessage); + ProgramInformation(const ProgramInformation&) = default; + ProgramInformation(ProgramInformation&&) = default; /// Destruction ~ProgramInformation() noexcept override = default; + ProgramInformation& operator=(const ProgramInformation&) = default; + ProgramInformation& operator=(ProgramInformation&&) = default; }; /** @@ -517,8 +569,12 @@ public: TypeError(); TypeError(const char* sMessage); TypeError(const std::string& sMessage); + TypeError(const TypeError&) = default; + TypeError(TypeError&&) = default; /// Destruction ~TypeError() noexcept override = default; + TypeError& operator=(const TypeError&) = default; + TypeError& operator=(TypeError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -533,8 +589,12 @@ public: ValueError(); ValueError(const char* sMessage); ValueError(const std::string& sMessage); + ValueError(const ValueError&) = default; + ValueError(ValueError&&) = default; /// Destruction ~ValueError() noexcept override = default; + ValueError& operator=(const ValueError&) = default; + ValueError& operator=(ValueError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -549,8 +609,12 @@ public: IndexError(); IndexError(const char* sMessage); IndexError(const std::string& sMessage); + IndexError(const IndexError&) = default; + IndexError(IndexError&&) = default; /// Destruction ~IndexError() noexcept override = default; + IndexError& operator=(const IndexError&) = default; + IndexError& operator=(IndexError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -561,8 +625,12 @@ public: NameError(); NameError(const char* sMessage); NameError(const std::string& sMessage); + NameError(const NameError&) = default; + NameError(NameError&&) = default; /// Destruction ~NameError() noexcept override = default; + NameError& operator=(const NameError&) = default; + NameError& operator=(NameError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -573,8 +641,12 @@ public: ImportError(); ImportError(const char* sMessage); ImportError(const std::string& sMessage); + ImportError(const ImportError&) = default; + ImportError(ImportError&&) = default; /// Destruction ~ImportError() noexcept override = default; + ImportError& operator=(const ImportError&) = default; + ImportError& operator=(ImportError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -589,8 +661,12 @@ public: AttributeError(); AttributeError(const char* sMessage); AttributeError(const std::string& sMessage); + AttributeError(const AttributeError&) = default; + AttributeError(AttributeError&&) = default; /// Destruction ~AttributeError() noexcept override = default; + AttributeError& operator=(const AttributeError&) = default; + AttributeError& operator=(AttributeError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -605,8 +681,12 @@ public: RuntimeError(); RuntimeError(const char* sMessage); RuntimeError(const std::string& sMessage); + RuntimeError(const RuntimeError&) = default; + RuntimeError(RuntimeError&&) = default; /// Destruction ~RuntimeError() noexcept override = default; + RuntimeError& operator=(const RuntimeError&) = default; + RuntimeError& operator=(RuntimeError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -621,8 +701,12 @@ public: BadGraphError(); BadGraphError(const char* sMessage); BadGraphError(const std::string& sMessage); + BadGraphError(const BadGraphError&) = default; + BadGraphError(BadGraphError&&) = default; /// Destruction ~BadGraphError() noexcept override = default; + BadGraphError& operator=(const BadGraphError&) = default; + BadGraphError& operator=(BadGraphError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -637,8 +721,12 @@ public: NotImplementedError(); NotImplementedError(const char* sMessage); NotImplementedError(const std::string& sMessage); + NotImplementedError(const NotImplementedError&) = default; + NotImplementedError(NotImplementedError&&) = default; /// Destruction ~NotImplementedError() noexcept override = default; + NotImplementedError& operator=(const NotImplementedError&) = default; + NotImplementedError& operator=(NotImplementedError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -653,8 +741,12 @@ public: ZeroDivisionError(); ZeroDivisionError(const char* sMessage); ZeroDivisionError(const std::string& sMessage); + ZeroDivisionError(const ZeroDivisionError&) = default; + ZeroDivisionError(ZeroDivisionError&&) = default; /// Destruction ~ZeroDivisionError() noexcept override = default; + ZeroDivisionError& operator=(const ZeroDivisionError&) = default; + ZeroDivisionError& operator=(ZeroDivisionError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -669,8 +761,12 @@ public: ReferenceError(); ReferenceError(const char* sMessage); ReferenceError(const std::string& sMessage); + ReferenceError(const ReferenceError&) = default; + ReferenceError(ReferenceError&&) = default; /// Destruction ~ReferenceError() noexcept override = default; + ReferenceError& operator=(const ReferenceError&) = default; + ReferenceError& operator=(ReferenceError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -686,8 +782,12 @@ public: ExpressionError(); ExpressionError(const char* sMessage); ExpressionError(const std::string& sMessage); + ExpressionError(const ExpressionError&) = default; + ExpressionError(ExpressionError&&) = default; /// Destruction ~ExpressionError() noexcept override = default; + ExpressionError& operator=(const ExpressionError&) = default; + ExpressionError& operator=(ExpressionError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -702,8 +802,12 @@ public: ParserError(); ParserError(const char* sMessage); ParserError(const std::string& sMessage); + ParserError(const ParserError&) = default; + ParserError(ParserError&&) = default; /// Destruction ~ParserError() noexcept override = default; + ParserError& operator=(const ParserError&) = default; + ParserError& operator=(ParserError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -718,8 +822,12 @@ public: UnicodeError(); UnicodeError(const char* sMessage); UnicodeError(const std::string& sMessage); + UnicodeError(const UnicodeError&) = default; + UnicodeError(UnicodeError&&) = default; /// Destruction ~UnicodeError() noexcept override = default; + UnicodeError& operator=(const UnicodeError&) = default; + UnicodeError& operator=(UnicodeError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -734,8 +842,12 @@ public: OverflowError(); OverflowError(const char* sMessage); OverflowError(const std::string& sMessage); + OverflowError(const OverflowError&) = default; + OverflowError(OverflowError&&) = default; /// Destruction ~OverflowError() noexcept override = default; + OverflowError& operator=(const OverflowError&) = default; + OverflowError& operator=(OverflowError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -750,8 +862,12 @@ public: UnderflowError(); UnderflowError(const char* sMessage); UnderflowError(const std::string& sMessage); + UnderflowError(const UnderflowError&) = default; + UnderflowError(UnderflowError&&) = default; /// Destruction ~UnderflowError() noexcept override = default; + UnderflowError& operator=(const UnderflowError&) = default; + UnderflowError& operator=(UnderflowError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -766,8 +882,12 @@ public: UnitsMismatchError(); UnitsMismatchError(const char* sMessage); UnitsMismatchError(const std::string& sMessage); + UnitsMismatchError(const UnitsMismatchError&) = default; + UnitsMismatchError(UnitsMismatchError&&) = default; /// Destruction ~UnitsMismatchError() noexcept override = default; + UnitsMismatchError& operator=(const UnitsMismatchError&) = default; + UnitsMismatchError& operator=(UnitsMismatchError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -783,8 +903,12 @@ public: CADKernelError(); CADKernelError(const char* sMessage); CADKernelError(const std::string& sMessage); + CADKernelError(const CADKernelError&) = default; + CADKernelError(CADKernelError&&) = default; /// Destruction ~CADKernelError() noexcept override = default; + CADKernelError& operator=(const CADKernelError&) = default; + CADKernelError& operator=(CADKernelError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -802,8 +926,12 @@ public: RestoreError(); RestoreError(const char* sMessage); RestoreError(const std::string& sMessage); + RestoreError(const RestoreError&) = default; + RestoreError(RestoreError&&) = default; /// Destruction ~RestoreError() noexcept override = default; + RestoreError& operator=(const RestoreError&) = default; + RestoreError& operator=(RestoreError&&) = default; PyObject* getPyExceptionType() const override; }; @@ -844,7 +972,7 @@ inline bool Exception::getTranslatable() const } inline void -Exception::setDebugInformation(const std::string& file, const int line, const std::string& function) +Exception::setDebugInformation(const std::string& file, int line, const std::string& function) { _file = file; _line = line; @@ -867,8 +995,10 @@ private: static void throw_signal(int signum); private: - struct sigaction new_action, old_action; - bool ok; + // clang-format off + struct sigaction new_action {}, old_action {}; + bool ok {false}; + // clang-format on }; #endif diff --git a/src/Base/ExceptionFactory.cpp b/src/Base/ExceptionFactory.cpp index 0c2f22e61d..d3816fef6d 100644 --- a/src/Base/ExceptionFactory.cpp +++ b/src/Base/ExceptionFactory.cpp @@ -33,16 +33,14 @@ ExceptionFactory* ExceptionFactory::_pcSingleton = nullptr; // NOLINT ExceptionFactory& ExceptionFactory::Instance() { if (!_pcSingleton) { - _pcSingleton = new ExceptionFactory; + _pcSingleton = new ExceptionFactory; // NOLINT } return *_pcSingleton; } void ExceptionFactory::Destruct() { - if (_pcSingleton) { - delete _pcSingleton; - } + delete _pcSingleton; _pcSingleton = nullptr; } @@ -56,7 +54,7 @@ void ExceptionFactory::raiseException(PyObject* pydict) const std::map::const_iterator pProd; - pProd = _mpcProducers.find(classname.c_str()); + pProd = _mpcProducers.find(classname); if (pProd != _mpcProducers.end()) { static_cast(pProd->second)->raiseException(pydict); } diff --git a/src/Base/ExceptionFactory.h b/src/Base/ExceptionFactory.h index 77e83cfab9..6cb32448df 100644 --- a/src/Base/ExceptionFactory.h +++ b/src/Base/ExceptionFactory.h @@ -75,14 +75,12 @@ public: ExceptionFactory::Instance().AddProducer(typeid(CLASS).name(), this); } - ~ExceptionProducer() override = default; - void raiseException(PyObject* pydict) const override { - CLASS c; - c.setPyObject(pydict); + CLASS cls; + cls.setPyObject(pydict); - throw c; + throw cls; } }; diff --git a/src/Base/Factory.cpp b/src/Base/Factory.cpp index b970f05e41..8b937d3228 100644 --- a/src/Base/Factory.cpp +++ b/src/Base/Factory.cpp @@ -50,9 +50,8 @@ void* Factory::Produce(const char* sClassName) const if (pProd != _mpcProducers.end()) { return pProd->second->Produce(); } - else { - return nullptr; - } + + return nullptr; } void Factory::AddProducer(const char* sClassName, AbstractProducer* pcProducer) @@ -91,9 +90,7 @@ ScriptFactorySingleton& ScriptFactorySingleton::Instance() void ScriptFactorySingleton::Destruct() { - if (_pcSingleton) { - delete _pcSingleton; - } + delete _pcSingleton; _pcSingleton = nullptr; } diff --git a/src/Base/Factory.h b/src/Base/Factory.h index 0900569b3f..9193c355aa 100644 --- a/src/Base/Factory.h +++ b/src/Base/Factory.h @@ -44,6 +44,8 @@ public: virtual ~AbstractProducer() = default; /// overwritten by a concrete producer to produce the needed object virtual void* Produce() const = 0; + + FC_DISABLE_COPY_MOVE(AbstractProducer) }; @@ -62,22 +64,25 @@ public: bool CanProduce(const char* sClassName) const; /// returns a list of all registered producer std::list CanProduce() const; + /// destruction + virtual ~Factory(); + + FC_DISABLE_COPY_MOVE(Factory) protected: /// produce a class with the given name void* Produce(const char* sClassName) const; - std::map _mpcProducers; /// construction Factory() = default; - /// destruction - virtual ~Factory(); + + std::map _mpcProducers; }; // -------------------------------------------------------------------- /** The ScriptFactorySingleton singleton */ -class BaseExport ScriptFactorySingleton: public Factory +class BaseExport ScriptFactorySingleton: public Factory // NOLINT { public: static ScriptFactorySingleton& Instance(); @@ -85,9 +90,12 @@ public: const char* ProduceScript(const char* sScriptName) const; -private: - static ScriptFactorySingleton* _pcSingleton; + FC_DISABLE_COPY_MOVE(ScriptFactorySingleton) +private: + static ScriptFactorySingleton* _pcSingleton; // NOLINT + +protected: ScriptFactorySingleton() = default; ~ScriptFactorySingleton() override = default; }; @@ -118,9 +126,12 @@ public: /// Produce an instance void* Produce() const override { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast(mScript); } + FC_DISABLE_COPY_MOVE(ScriptProducer) + private: const char* mScript; }; diff --git a/src/Base/FileInfo.cpp b/src/Base/FileInfo.cpp index e441b7789f..ee70cb4f9a 100644 --- a/src/Base/FileInfo.cpp +++ b/src/Base/FileInfo.cpp @@ -93,21 +93,21 @@ std::wstring ConvertToWideString(const std::string& string) // FileInfo -FileInfo::FileInfo(const char* _FileName) +FileInfo::FileInfo(const char* fileName) { - setFile(_FileName); + setFile(fileName); } -FileInfo::FileInfo(const std::string& _FileName) +FileInfo::FileInfo(const std::string& fileName) { - setFile(_FileName.c_str()); + setFile(fileName.c_str()); } const std::string& FileInfo::getTempPath() { static std::string tempPath; - if (tempPath == "") { + if (tempPath.empty()) { #ifdef FC_OS_WIN32 wchar_t buf[MAX_PATH + 2]; GetTempPathW(MAX_PATH + 1, buf); @@ -218,13 +218,13 @@ boost::filesystem::path FileInfo::stringToPath(const std::string& str) return path; } -std::string FileInfo::pathToString(const boost::filesystem::path& p) +std::string FileInfo::pathToString(const boost::filesystem::path& path) { #if defined(FC_OS_WIN32) std::wstring_convert> converter; - return converter.to_bytes(p.wstring()); + return converter.to_bytes(path.wstring()); #else - return p.string(); + return path.string(); #endif } @@ -286,9 +286,8 @@ std::string FileInfo::fileNamePure() const if (pos != std::string::npos) { return temp.substr(0, pos); } - else { - return temp; - } + + return temp; } std::wstring FileInfo::toStdWString() const @@ -332,12 +331,9 @@ bool FileInfo::hasExtension(const char* Ext) const bool FileInfo::hasExtension(std::initializer_list Exts) const { - for (const char* Ext : Exts) { - if (hasExtension(Ext)) { - return true; - } - } - return false; + return std::any_of(Exts.begin(), Exts.end(), [this](const char* ext) { + return hasExtension(ext); + }); } bool FileInfo::exists() const @@ -405,7 +401,9 @@ bool FileInfo::isFile() const } return ok; #else - struct stat st; + // clang-format off + struct stat st {}; + // clang-format on if (stat(FileName.c_str(), &st) != 0) { return false; } diff --git a/src/Base/FileInfo.h b/src/Base/FileInfo.h index 4cddf20617..0f120386a6 100644 --- a/src/Base/FileInfo.h +++ b/src/Base/FileInfo.h @@ -59,8 +59,8 @@ public: }; /// Construction - FileInfo(const char* _FileName = ""); - FileInfo(const std::string& _FileName); + FileInfo(const char* fileName = ""); + FileInfo(const std::string& fileName); /// Set a new file name void setFile(const char* name); /// Set a new file name @@ -158,7 +158,7 @@ public: /// Get the path to the dir which is considered to temp files static const std::string& getTempPath(); /// Convert from filesystem path to string - static std::string pathToString(const boost::filesystem::path& p); + static std::string pathToString(const boost::filesystem::path& path); /// Convert from string to filesystem path static boost::filesystem::path stringToPath(const std::string& str); //@} diff --git a/src/Base/FileTemplate.cpp b/src/Base/FileTemplate.cpp index 09da6cf4ff..6533bd7d18 100644 --- a/src/Base/FileTemplate.cpp +++ b/src/Base/FileTemplate.cpp @@ -38,12 +38,19 @@ using namespace Base; */ ClassTemplate::ClassTemplate() = default; +ClassTemplate::ClassTemplate(const ClassTemplate&) = default; + +ClassTemplate::ClassTemplate(ClassTemplate&&) = default; + /** * A destructor. * A more elaborate description of the destructor. */ ClassTemplate::~ClassTemplate() = default; +ClassTemplate& ClassTemplate::operator=(const ClassTemplate&) = default; + +ClassTemplate& ClassTemplate::operator=(ClassTemplate&&) = default; //************************************************************************** // separator for other implementation aspects diff --git a/src/Base/FileTemplate.h b/src/Base/FileTemplate.h index f509b8cae9..e2b61435d8 100644 --- a/src/Base/FileTemplate.h +++ b/src/Base/FileTemplate.h @@ -86,9 +86,13 @@ class BaseExport ClassTemplate public: /// Construction ClassTemplate(); + ClassTemplate(const ClassTemplate&); + ClassTemplate(ClassTemplate&&); /// Destruction virtual ~ClassTemplate(); + ClassTemplate& operator=(const ClassTemplate&); + ClassTemplate& operator=(ClassTemplate&&); int testMe(int a, const char* s); /** diff --git a/src/Base/FutureWatcherProgress.cpp b/src/Base/FutureWatcherProgress.cpp index 0fbf90c05b..ab2de29e2e 100644 --- a/src/Base/FutureWatcherProgress.cpp +++ b/src/Base/FutureWatcherProgress.cpp @@ -35,12 +35,12 @@ FutureWatcherProgress::FutureWatcherProgress(const char* text, unsigned int step FutureWatcherProgress::~FutureWatcherProgress() = default; -void FutureWatcherProgress::progressValueChanged(int v) +void FutureWatcherProgress::progressValueChanged(int value) { if (steps == 0) { return; } - unsigned int step = (100 * static_cast(v)) / steps; + unsigned int step = (100 * static_cast(value)) / steps; if (step > current) { current = step; seq.next(); diff --git a/src/Base/GeometryPyCXX.cpp b/src/Base/GeometryPyCXX.cpp index 33738dafa5..dc96d98314 100644 --- a/src/Base/GeometryPyCXX.cpp +++ b/src/Base/GeometryPyCXX.cpp @@ -30,6 +30,7 @@ #include "VectorPy.h" +// NOLINTBEGIN(readability-identifier-length) int Py::Vector::Vector_TypeCheck(PyObject* obj) { return PyObject_TypeCheck(obj, &(Base::VectorPy::Type)); @@ -40,22 +41,22 @@ bool Py::Vector::accepts(PyObject* obj) const if (obj && Vector_TypeCheck(obj)) { return true; } - else if (obj && PySequence_Check(obj)) { + if (obj && PySequence_Check(obj)) { return (PySequence_Size(obj) == 3); } return false; } -Py::Vector::Vector(const Base::Vector3d& v) +Py::Vector::Vector(const Base::Vector3d& vec) { - set(new Base::VectorPy(v), true); + set(new Base::VectorPy(vec), true); validate(); } -Py::Vector::Vector(const Base::Vector3f& v) +Py::Vector::Vector(const Base::Vector3f& vec) { - set(new Base::VectorPy(v), true); + set(new Base::VectorPy(vec), true); validate(); } @@ -68,15 +69,15 @@ Py::Vector& Py::Vector::operator=(PyObject* rhsp) return *this; } -Py::Vector& Py::Vector::operator=(const Base::Vector3d& v) +Py::Vector& Py::Vector::operator=(const Base::Vector3d& vec) { - set(new Base::VectorPy(v), true); + set(new Base::VectorPy(vec), true); return *this; } -Py::Vector& Py::Vector::operator=(const Base::Vector3f& v) +Py::Vector& Py::Vector::operator=(const Base::Vector3f& vec) { - set(new Base::VectorPy(v), true); + set(new Base::VectorPy(vec), true); return *this; } @@ -85,9 +86,8 @@ Base::Vector3d Py::Vector::toVector() const if (Vector_TypeCheck(ptr())) { return static_cast(ptr())->value(); } - else { - return Base::getVectorFromTuple(ptr()); - } + + return Base::getVectorFromTuple(ptr()); } namespace Base @@ -103,51 +103,52 @@ PyTypeObject* Vector2dPy::type_object() return Py::PythonClass::type_object(); } -bool Vector2dPy::check(PyObject* p) +bool Vector2dPy::check(PyObject* py) { - return Py::PythonClass::check(p); + return Py::PythonClass::check(py); } -Py::PythonClassObject Vector2dPy::create(const Vector2d& v) +Py::PythonClassObject Vector2dPy::create(const Vector2d& vec) { - return create(v.x, v.y); + return create(vec.x, vec.y); } -Py::PythonClassObject Vector2dPy::create(double x, double y) +Py::PythonClassObject Vector2dPy::create(double vx, double vy) { Py::Callable class_type(type()); Py::Tuple arg(2); - arg.setItem(0, Py::Float(x)); - arg.setItem(1, Py::Float(y)); - Py::PythonClassObject o = + arg.setItem(0, Py::Float(vx)); + arg.setItem(1, Py::Float(vy)); + Py::PythonClassObject py = Py::PythonClassObject(class_type.apply(arg, Py::Dict())); - return o; + return py; } Vector2dPy::Vector2dPy(Py::PythonClassInstance* self, Py::Tuple& args, Py::Dict& kwds) : Py::PythonClass::PythonClass(self, args, kwds) { - double x = 0, y = 0; - if (!PyArg_ParseTuple(args.ptr(), "|dd", &x, &y)) { + double vx = 0; + double vy = 0; + if (!PyArg_ParseTuple(args.ptr(), "|dd", &vx, &vy)) { throw Py::Exception(); } - v.x = x; - v.y = y; + v.x = vx; + v.y = vy; } Vector2dPy::~Vector2dPy() = default; Py::Object Vector2dPy::repr() { - Py::Float x(v.x); - Py::Float y(v.y); + Py::Float vx(v.x); + Py::Float vy(v.y); std::stringstream str; str << "Vector2 ("; - str << static_cast(x.repr()) << ", " << static_cast(y.repr()); + str << static_cast(vx.repr()) << ", " << static_cast(vy.repr()); str << ")"; - return Py::String(str.str()); + return Py::String(str.str()); // NOLINT } Py::Object Vector2dPy::getattro(const Py::String& name_) @@ -161,17 +162,16 @@ Py::Object Vector2dPy::getattro(const Py::String& name_) Py::Dict attr; attr.setItem(Py::String("x"), Py::Float(v.x)); attr.setItem(Py::String("y"), Py::Float(v.y)); - return attr; + return attr; // NOLINT } - else if (name == "x") { - return Py::Float(v.x); + if (name == "x") { + return Py::Float(v.x); // NOLINT } - else if (name == "y") { - return Py::Float(v.y); - } - else { - return genericGetAttro(name_); + if (name == "y") { + return Py::Float(v.y); // NOLINT } + + return genericGetAttro(name_); } int Vector2dPy::setattro(const Py::String& name_, const Py::Object& value) @@ -182,28 +182,27 @@ int Vector2dPy::setattro(const Py::String& name_, const Py::Object& value) v.x = static_cast(Py::Float(value)); return 0; } - else if (name == "y" && !value.isNull()) { + if (name == "y" && !value.isNull()) { v.y = static_cast(Py::Float(value)); return 0; } - else { - return genericSetAttro(name_, value); - } + + return genericSetAttro(name_, value); } Py::Object Vector2dPy::number_negative() { - return create(-v.x, -v.y); + return create(-v.x, -v.y); // NOLINT } Py::Object Vector2dPy::number_positive() { - return create(v.x, v.y); + return create(v.x, v.y); // NOLINT } Py::Object Vector2dPy::number_absolute() { - return create(fabs(v.x), fabs(v.y)); + return create(fabs(v.x), fabs(v.y)); // NOLINT } Py::Object Vector2dPy::number_invert() @@ -223,32 +222,31 @@ Py::Object Vector2dPy::number_float() Py::Object Vector2dPy::number_add(const Py::Object& py) { - Vector2d u(Py::toVector2d(py)); - u = v + u; - return create(u); + Vector2d vec(Py::toVector2d(py)); + vec = v + vec; + return create(vec); // NOLINT } Py::Object Vector2dPy::number_subtract(const Py::Object& py) { - Vector2d u(Py::toVector2d(py)); - u = v - u; - return create(u); + Vector2d vec(Py::toVector2d(py)); + vec = v - vec; + return create(vec); // NOLINT } Py::Object Vector2dPy::number_multiply(const Py::Object& py) { if (PyObject_TypeCheck(py.ptr(), Vector2dPy::type_object())) { - Vector2d u(Py::toVector2d(py)); - double d = v * u; - return Py::Float(d); + Vector2d vec(Py::toVector2d(py)); + double scalar = v * vec; + return Py::Float(scalar); // NOLINT } - else if (py.isNumeric()) { - double d = static_cast(Py::Float(py)); - return create(v * d); - } - else { - throw Py::TypeError("Argument must be Vector2d or Float"); + if (py.isNumeric()) { + double scale = static_cast(Py::Float(py)); + return create(v * scale); // NOLINT } + + throw Py::TypeError("Argument must be Vector2d or Float"); } Py::Object Vector2dPy::number_remainder(const Py::Object&) @@ -297,40 +295,40 @@ Py::Object Vector2dPy::isNull(const Py::Tuple& args) if (args.size() > 0) { tol = static_cast(Py::Float(args[0])); } - return Py::Boolean(v.IsNull(tol)); + return Py::Boolean(v.IsNull(tol)); // NOLINT } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, isNull) Py::Object Vector2dPy::length(const Py::Tuple&) { - return Py::Float(v.Length()); + return Py::Float(v.Length()); // NOLINT } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, length) Py::Object Vector2dPy::atan2(const Py::Tuple&) { - return Py::Float(v.Angle()); + return Py::Float(v.Angle()); // NOLINT } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, atan2) Py::Object Vector2dPy::square(const Py::Tuple&) { - return Py::Float(v.Sqr()); + return Py::Float(v.Sqr()); // NOLINT } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, square) Py::Object Vector2dPy::scale(const Py::Tuple& args) { - double f = static_cast(Py::Float(args[0])); - v.Scale(f); + double value = static_cast(Py::Float(args[0])); + v.Scale(value); return Py::None(); } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, scale) Py::Object Vector2dPy::rotate(const Py::Tuple& args) { - double f = static_cast(Py::Float(args[0])); - v.Rotate(f); + double value = static_cast(Py::Float(args[0])); + v.Rotate(value); return Py::None(); } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, rotate) @@ -344,42 +342,43 @@ PYCXX_VARARGS_METHOD_DECL(Vector2dPy, normalize) Py::Object Vector2dPy::perpendicular(const Py::Tuple& args) { - bool f = static_cast(Py::Boolean(args[0])); - Base::Vector2d p = v.Perpendicular(f); - return create(p); + bool value = static_cast(Py::Boolean(args[0])); + Base::Vector2d pnt = v.Perpendicular(value); + return create(pnt); // NOLINT } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, perpendicular) Py::Object Vector2dPy::distance(const Py::Tuple& args) { - Base::Vector2d p = Py::toVector2d(args[0]); - return Py::Float(p.Distance(v)); + Base::Vector2d pnt = Py::toVector2d(args[0]); + return Py::Float(pnt.Distance(v)); // NOLINT } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, distance) Py::Object Vector2dPy::isEqual(const Py::Tuple& args) { - Base::Vector2d p = Py::toVector2d(args[0]); - double f = static_cast(Py::Float(args[1])); - return Py::Boolean(v.IsEqual(p, f)); + Base::Vector2d pnt = Py::toVector2d(args[0]); + double tol = static_cast(Py::Float(args[1])); + return Py::Boolean(v.IsEqual(pnt, tol)); // NOLINT } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, isEqual) Py::Object Vector2dPy::getAngle(const Py::Tuple& args) { - Base::Vector2d p = Py::toVector2d(args[0]); - return Py::Float(v.GetAngle(p)); + Base::Vector2d vec = Py::toVector2d(args[0]); + return Py::Float(v.GetAngle(vec)); // NOLINT } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, getAngle) Py::Object Vector2dPy::projectToLine(const Py::Tuple& args) { - Base::Vector2d p = Py::toVector2d(args[0]); - Base::Vector2d d = Py::toVector2d(args[1]); - v.ProjectToLine(p, d); + Base::Vector2d pnt1 = Py::toVector2d(args[0]); + Base::Vector2d pnt2 = Py::toVector2d(args[1]); + v.ProjectToLine(pnt1, pnt2); return Py::None(); } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, projectToLine) +// NOLINTEND(readability-identifier-length) void Vector2dPy::init_type() { diff --git a/src/Base/GeometryPyCXX.h b/src/Base/GeometryPyCXX.h index 78602b70b3..709c8a689e 100644 --- a/src/Base/GeometryPyCXX.h +++ b/src/Base/GeometryPyCXX.h @@ -40,18 +40,18 @@ namespace Base { template -inline Vector3 getVectorFromTuple(PyObject* o) +inline Vector3 getVectorFromTuple(PyObject* py) { - Py::Sequence tuple(o); + Py::Sequence tuple(py); if (tuple.size() != 3) { throw Py::ValueError("Expected sequence of size 3"); } - T x = static_cast(Py::Float(tuple[0])); - T y = static_cast(Py::Float(tuple[1])); - T z = static_cast(Py::Float(tuple[2])); + T vx = static_cast(Py::Float(tuple[0])); + T vy = static_cast(Py::Float(tuple[1])); + T vz = static_cast(Py::Float(tuple[2])); - return Vector3(x, y, z); + return Vector3(vx, vy, vz); } class BaseExport Vector2dPy: public Py::PythonClass // NOLINT @@ -59,10 +59,10 @@ class BaseExport Vector2dPy: public Py::PythonClass // NOLINT public: static Py::PythonType& behaviors(); static PyTypeObject* type_object(); - static bool check(PyObject* p); + static bool check(PyObject* py); static Py::PythonClassObject create(const Vector2d&); - static Py::PythonClassObject create(double x, double y); + static Py::PythonClassObject create(double vx, double vy); Vector2dPy(Py::PythonClassInstance* self, Py::Tuple& args, Py::Dict& kwds); ~Vector2dPy() override; @@ -78,10 +78,10 @@ public: { v = n; } - inline void setValue(double x, double y) + inline void setValue(double vx, double vy) { - v.x = x; - v.y = y; + v.x = vx; + v.y = vy; } /** @name methods for group handling */ @@ -152,14 +152,14 @@ public: } Vector(const Vector& ob) - : Object(*ob) + : Object(ob) { validate(); } explicit Vector(const Base::Vector3d&); explicit Vector(const Base::Vector3f&); - bool accepts(PyObject* pyob) const override; + bool accepts(PyObject* obj) const override; Vector(const Object& other) : Object(other.ptr()) @@ -220,9 +220,9 @@ public: set(new PyT(new T()), true); validate(); } - explicit GeometryT(const T& v) + explicit GeometryT(const T& val) { - set(new PyT(new T(v)), true); + set(new PyT(new T(val)), true); validate(); } GeometryT(const Object& other) @@ -236,7 +236,8 @@ public: } GeometryT& operator=(const Object& rhs) { - return (*this = *rhs); + *this = *rhs; + return *this; } GeometryT& operator=(PyObject* rhsp) { @@ -246,9 +247,9 @@ public: set(rhsp, false); return *this; } - GeometryT& operator=(const T& v) + GeometryT& operator=(const T& val) { - set(new PyT(v), true); + set(new PyT(val), true); return *this; } const T& getValue() const @@ -256,8 +257,8 @@ public: // cast the PyObject pointer to the matching sub-class // and call then the defined member function PyT* py = static_cast(ptr()); - T* v = (py->*valuePtr)(); - return *v; + T* val = (py->*valuePtr)(); + return *val; } operator T() const { diff --git a/src/Base/Handle.cpp b/src/Base/Handle.cpp index b64d10d7d2..9a8e7589f0 100644 --- a/src/Base/Handle.cpp +++ b/src/Base/Handle.cpp @@ -76,7 +76,7 @@ int Handled::getRefCount() const return static_cast(*_lRefCount); } -Handled& Handled::operator=(const Handled&) +Handled& Handled::operator=(const Handled& /*unused*/) { // we must not assign _lRefCount return *this; diff --git a/src/Base/Handle.h b/src/Base/Handle.h index a67754dfb4..fc8f6ccc25 100644 --- a/src/Base/Handle.h +++ b/src/Base/Handle.h @@ -52,8 +52,8 @@ public: : _toHandle(nullptr) {} - Reference(T* p) - : _toHandle(p) + Reference(T* pointer) + : _toHandle(pointer) { if (_toHandle) { _toHandle->ref(); @@ -61,8 +61,8 @@ public: } /** Copy constructor */ - Reference(const Reference& p) - : _toHandle(p._toHandle) + Reference(const Reference& ref) + : _toHandle(ref._toHandle) { if (_toHandle) { _toHandle->ref(); @@ -85,16 +85,16 @@ public: // operator implementation /** Assign operator from a pointer */ - Reference& operator=(T* p) + Reference& operator=(T* pointer) { // check if we want to reassign the same object - if (_toHandle == p) { + if (_toHandle == pointer) { return *this; } if (_toHandle) { _toHandle->unref(); } - _toHandle = p; + _toHandle = pointer; if (_toHandle) { _toHandle->ref(); } @@ -102,16 +102,16 @@ public: } /** Assign operator from a handle */ - Reference& operator=(const Reference& p) + Reference& operator=(const Reference& ref) { // check if we want to reassign the same object - if (_toHandle == p._toHandle) { + if (_toHandle == ref._toHandle) { return *this; } if (_toHandle) { _toHandle->unref(); } - _toHandle = p._toHandle; + _toHandle = ref._toHandle; if (_toHandle) { _toHandle->ref(); } diff --git a/src/Base/InputSource.h b/src/Base/InputSource.h index a5fe42630c..a56d5bc507 100644 --- a/src/Base/InputSource.h +++ b/src/Base/InputSource.h @@ -63,7 +63,9 @@ public: // Unimplemented constructors and operators // ----------------------------------------------------------------------- StdInputStream(const StdInputStream&) = delete; + StdInputStream(StdInputStream&&) = delete; StdInputStream& operator=(const StdInputStream&) = delete; + StdInputStream& operator=(StdInputStream&&) = delete; private: // ----------------------------------------------------------------------- @@ -91,7 +93,9 @@ public: XERCES_CPP_NAMESPACE_QUALIFIER BinInputStream* makeStream() const override; StdInputSource(const StdInputSource&) = delete; + StdInputSource(StdInputSource&&) = delete; StdInputSource& operator=(const StdInputSource&) = delete; + StdInputSource& operator=(StdInputSource&&) = delete; private: std::istream& stream; diff --git a/src/Base/Interpreter.cpp b/src/Base/Interpreter.cpp index 7f788e847c..9c5b7be311 100644 --- a/src/Base/Interpreter.cpp +++ b/src/Base/Interpreter.cpp @@ -115,9 +115,9 @@ void PyException::raiseException() } if (_exceptionType == Base::PyExc_FC_FreeCADAbort) { - Base::AbortException e(_sErrMsg.c_str()); - e.setReported(_isReported); - throw e; + Base::AbortException exc(_sErrMsg.c_str()); + exc.setReported(_isReported); + throw exc; } throw *this; @@ -160,7 +160,10 @@ SystemExitException::SystemExitException() long int errCode = 1; std::string errMsg = "System exit"; - PyObject *type {}, *value {}, *traceback {}, *code {}; + PyObject* type {}; + PyObject* value {}; + PyObject* traceback {}; + PyObject* code {}; PyGILStateLocker locker; PyErr_Fetch(&type, &value, &traceback); @@ -228,7 +231,9 @@ InterpreterSingleton::~InterpreterSingleton() = default; std::string InterpreterSingleton::runString(const char* sCmd) { - PyObject *module {}, *dict {}, *presult {}; /* "exec code in d, d" */ + PyObject* module {}; + PyObject* dict {}; + PyObject* presult {}; PyGILStateLocker locker; module = PP_Load_Module("__main__"); /* get module, init python */ @@ -246,10 +251,9 @@ std::string InterpreterSingleton::runString(const char* sCmd) if (PyErr_ExceptionMatches(PyExc_SystemExit)) { throw SystemExitException(); } - else { - PyException::ThrowException(); - return {}; // just to quieten code analyzers - } + + PyException::ThrowException(); + return {}; // just to quieten code analyzers } PyObject* repr = PyObject_Repr(presult); @@ -259,10 +263,9 @@ std::string InterpreterSingleton::runString(const char* sCmd) Py_DECREF(repr); return ret; } - else { - PyErr_Clear(); - return {}; - } + + PyErr_Clear(); + return {}; } /** runStringWithKey(psCmd, key, key_initial_value) @@ -292,16 +295,15 @@ std::string InterpreterSingleton::runStringWithKey(const char* psCmd, if (PyErr_ExceptionMatches(PyExc_SystemExit)) { throw SystemExitException(); } - else { - PyException::ThrowException(); - return {}; // just to quieten code analyzers - } + + PyException::ThrowException(); + return {}; // just to quieten code analyzers } Py_DECREF(presult); Py::Object key_return_value = localDictionary.getItem(key); if (!key_return_value.isString()) { - key_return_value = key_return_value.str(); + key_return_value = key_return_value.str(); // NOLINT } Py::Bytes str = Py::String(key_return_value).encode("utf-8", "~E~"); @@ -311,7 +313,9 @@ std::string InterpreterSingleton::runStringWithKey(const char* psCmd, Py::Object InterpreterSingleton::runStringObject(const char* sCmd) { - PyObject *module {}, *dict {}, *presult {}; /* "exec code in d, d" */ + PyObject* module {}; + PyObject* dict {}; + PyObject* presult {}; PyGILStateLocker locker; module = PP_Load_Module("__main__"); /* get module, init python */ @@ -329,9 +333,8 @@ Py::Object InterpreterSingleton::runStringObject(const char* sCmd) if (PyErr_ExceptionMatches(PyExc_SystemExit)) { throw SystemExitException(); } - else { - throw PyException(); - } + + throw PyException(); } return Py::asObject(presult); @@ -340,7 +343,9 @@ Py::Object InterpreterSingleton::runStringObject(const char* sCmd) void InterpreterSingleton::systemExit() { /* This code is taken from the original Python code */ - PyObject *exception {}, *value {}, *tb {}; + PyObject* exception {}; + PyObject* value {}; + PyObject* tb {}; int exitcode = 0; PyErr_Fetch(&exception, &value, &tb); @@ -383,7 +388,9 @@ done: void InterpreterSingleton::runInteractiveString(const char* sCmd) { - PyObject *module {}, *dict {}, *presult {}; /* "exec code in d, d" */ + PyObject* module {}; + PyObject* dict {}; + PyObject* presult {}; PyGILStateLocker locker; module = PP_Load_Module("__main__"); /* get module, init python */ @@ -402,7 +409,9 @@ void InterpreterSingleton::runInteractiveString(const char* sCmd) } /* get latest python exception information */ /* and print the error to the error output */ - PyObject *errobj {}, *errdata {}, *errtraceback {}; + PyObject* errobj {}; + PyObject* errdata {}; + PyObject* errtraceback {}; PyErr_Fetch(&errobj, &errdata, &errtraceback); RuntimeError exc(""); // do not use PyException since this clears the error indicator @@ -417,9 +426,8 @@ void InterpreterSingleton::runInteractiveString(const char* sCmd) } throw exc; } - else { - Py_DECREF(presult); - } + + Py_DECREF(presult); } void InterpreterSingleton::runFile(const char* pxFileName, bool local) @@ -432,7 +440,8 @@ void InterpreterSingleton::runFile(const char* pxFileName, bool local) #endif if (fp) { PyGILStateLocker locker; - PyObject *module {}, *dict {}; + PyObject* module {}; + PyObject* dict {}; module = PyImport_AddModule("__main__"); dict = PyModule_GetDict(module); if (local) { @@ -466,9 +475,8 @@ void InterpreterSingleton::runFile(const char* pxFileName, bool local) if (PyErr_ExceptionMatches(PyExc_SystemExit)) { throw SystemExitException(); } - else { - throw PyException(); - } + + throw PyException(); } Py_DECREF(result); } @@ -490,9 +498,8 @@ bool InterpreterSingleton::loadModule(const char* psModName) if (PyErr_ExceptionMatches(PyExc_SystemExit)) { throw SystemExitException(); } - else { - throw PyException(); - } + + throw PyException(); } return true; @@ -744,7 +751,9 @@ void InterpreterSingleton::runMethod(PyObject* pobject, const char* argfmt, ...) /* convert to python */ { - PyObject *pmeth {}, *pargs {}, *presult {}; + PyObject* pmeth {}; + PyObject* pargs {}; + PyObject* presult {}; va_list argslist; /* "pobject.method(args)" */ va_start(argslist, argfmt); @@ -784,7 +793,9 @@ void InterpreterSingleton::runMethod(PyObject* pobject, PyObject* InterpreterSingleton::getValue(const char* key, const char* result_var) { - PyObject *module {}, *dict {}, *presult {}; /* "exec code in d, d" */ + PyObject* module {}; + PyObject* dict {}; + PyObject* presult {}; PyGILStateLocker locker; module = PP_Load_Module("__main__"); /* get module, init python */ @@ -825,7 +836,7 @@ void InterpreterSingleton::dbgUnsetBreakPoint(unsigned int /*uiLineNumber*/) void InterpreterSingleton::dbgStep() {} -const std::string InterpreterSingleton::strToPython(const char* Str) +std::string InterpreterSingleton::strToPython(const char* Str) { std::string result; const char* It = Str; @@ -859,40 +870,38 @@ int getSWIGVersionFromModule(const std::string& module) if (it != moduleMap.end()) { return it->second; } - else { - try { - // Get the module and check its __file__ attribute - Py::Dict dict(PyImport_GetModuleDict()); - if (!dict.hasKey(module)) { - return 0; - } - Py::Module mod(module); - Py::String file(mod.getAttr("__file__")); - std::string filename = (std::string)file; - // file can have the extension .py or .pyc - filename = filename.substr(0, filename.rfind('.')); - filename += ".py"; - boost::regex rx("^# Version ([1-9])\\.([0-9])\\.([0-9]+)"); - boost::cmatch what; + try { + // Get the module and check its __file__ attribute + Py::Dict dict(PyImport_GetModuleDict()); + if (!dict.hasKey(module)) { + return 0; + } + Py::Module mod(module); + Py::String file(mod.getAttr("__file__")); + std::string filename = (std::string)file; + // file can have the extension .py or .pyc + filename = filename.substr(0, filename.rfind('.')); + filename += ".py"; + boost::regex rx("^# Version ([1-9])\\.([0-9])\\.([0-9]+)"); + boost::cmatch what; - std::string line; - Base::FileInfo fi(filename); + std::string line; + Base::FileInfo fi(filename); - Base::ifstream str(fi, std::ios::in); - while (str && std::getline(str, line)) { - if (boost::regex_match(line.c_str(), what, rx)) { - int major = std::atoi(what[1].first); - int minor = std::atoi(what[2].first); - int micro = std::atoi(what[3].first); - int version = (major << 16) + (minor << 8) + micro; - moduleMap[module] = version; - return version; - } + Base::ifstream str(fi, std::ios::in); + while (str && std::getline(str, line)) { + if (boost::regex_match(line.c_str(), what, rx)) { + int major = std::atoi(what[1].first); + int minor = std::atoi(what[2].first); + int micro = std::atoi(what[3].first); + int version = (major << 16) + (minor << 8) + micro; + moduleMap[module] = version; + return version; } } - catch (Py::Exception& e) { - e.clear(); - } + } + catch (Py::Exception& e) { + e.clear(); } #if (defined(HAVE_SWIG) && (HAVE_SWIG == 1)) diff --git a/src/Base/Interpreter.h b/src/Base/Interpreter.h index 1a9535cd0b..43b85ee0d7 100644 --- a/src/Base/Interpreter.h +++ b/src/Base/Interpreter.h @@ -47,6 +47,7 @@ #include "Exception.h" +// NOLINTBEGIN /** Helper macro to obtain callable from an object * * @param _pyobj: PyObject pointer @@ -79,6 +80,7 @@ if (PyObject_HasAttrString(_pyobj, _name)) \ _var = Py::asObject(PyObject_GetAttrString(_pyobj, _name)); \ } while (0) +// NOLINTEND namespace Base @@ -94,8 +96,12 @@ public: /// constructor does the whole job PyException(); PyException(const Py::Object& obj); + PyException(const PyException&) = default; + PyException(PyException&&) = default; ~PyException() noexcept override; + PyException& operator=(const PyException&) = default; + PyException& operator=(PyException&&) = default; void raiseException(); /// this method determines if the original exception @@ -120,7 +126,7 @@ public: /// Sets the Python error indicator and an error message void setPyException() const override; -protected: +private: std::string _stackTrace; std::string _errorType; PyObject* _exceptionType; @@ -153,7 +159,11 @@ class BaseExport SystemExitException: public Exception { public: SystemExitException(); + SystemExitException(const SystemExitException&) = default; + SystemExitException(SystemExitException&&) = default; ~SystemExitException() noexcept override = default; + SystemExitException& operator=(const SystemExitException&) = default; + SystemExitException& operator=(SystemExitException&&) = default; long getExitCode() const { return _exitCode; @@ -175,13 +185,18 @@ class BaseExport PyGILStateLocker public: PyGILStateLocker() { - gstate = PyGILState_Ensure(); + gstate = PyGILState_Ensure(); // NOLINT } ~PyGILStateLocker() { PyGILState_Release(gstate); } + PyGILStateLocker(const PyGILStateLocker&) = delete; + PyGILStateLocker(PyGILStateLocker&&) = delete; + PyGILStateLocker& operator=(const PyGILStateLocker&) = delete; + PyGILStateLocker& operator=(PyGILStateLocker&&) = delete; + private: PyGILState_STATE gstate; }; @@ -201,7 +216,7 @@ public: PyGILStateRelease() { // release the global interpreter lock - state = PyEval_SaveThread(); + state = PyEval_SaveThread(); // NOLINT } ~PyGILStateRelease() { @@ -209,6 +224,11 @@ public: PyEval_RestoreThread(state); } + PyGILStateRelease(const PyGILStateRelease&) = delete; + PyGILStateRelease(PyGILStateRelease&&) = delete; + PyGILStateRelease& operator=(const PyGILStateRelease&) = delete; + PyGILStateRelease& operator=(PyGILStateRelease&&) = delete; + private: PyThreadState* state; }; @@ -224,6 +244,11 @@ public: InterpreterSingleton(); ~InterpreterSingleton(); + InterpreterSingleton(const InterpreterSingleton&) = delete; + InterpreterSingleton(InterpreterSingleton&&) = delete; + InterpreterSingleton& operator=(const InterpreterSingleton&) = delete; + InterpreterSingleton& operator=(InterpreterSingleton&&) = delete; + /** @name execution methods */ //@{ @@ -305,7 +330,7 @@ public: //@{ /// generate a SWIG object PyObject* - createSWIGPointerObj(const char* Modole, const char* TypeName, void* Pointer, int own); + createSWIGPointerObj(const char* Module, const char* TypeName, void* Pointer, int own); bool convertSWIGPointerObj(const char* Module, const char* TypeName, PyObject* obj, @@ -333,8 +358,8 @@ public: */ //@{ /// replaces all char with escapes for usage in python console - static const std::string strToPython(const char* Str); - static const std::string strToPython(const std::string& Str) + static std::string strToPython(const char* Str); + static std::string strToPython(const std::string& Str) { return strToPython(Str.c_str()); } diff --git a/src/Base/Matrix.cpp b/src/Base/Matrix.cpp index a530b46708..065fc1b569 100644 --- a/src/Base/Matrix.cpp +++ b/src/Base/Matrix.cpp @@ -540,6 +540,7 @@ void Matrix4D::inverse() using Matrix = double*; +// NOLINTBEGIN void Matrix_gauss(Matrix a, Matrix b) { int ipiv[4], indxr[4], indxc[4]; @@ -617,6 +618,7 @@ void Matrix_gauss(Matrix a, Matrix b) } } } +// NOLINTEND void Matrix4D::inverseOrthogonal() { @@ -967,8 +969,7 @@ std::array Matrix4D::decompose() const std::array dirs = {Vector3d(1., 0., 0.), Vector3d(0., 1., 0.), Vector3d(0., 0., 1.)}; - int i; - for (i = 0; i < 3; i++) { + for (int i = 0; i < 3; i++) { if (residualMatrix.getCol(i).IsNull()) { continue; } @@ -978,24 +979,23 @@ std::array Matrix4D::decompose() const prim_dir = i; continue; } - else { - Vector3d cross = dirs[prim_dir].Cross(residualMatrix.getCol(i)); - if (cross.IsNull()) { - continue; - } - cross.Normalize(); - int last_dir = 3 - i - prim_dir; - if (i - prim_dir == 1) { - dirs[last_dir] = cross; - dirs[i] = cross.Cross(dirs[prim_dir]); - } - else { - dirs[last_dir] = -cross; - dirs[i] = dirs[prim_dir].Cross(-cross); - } - prim_dir = -2; // done - break; + + Vector3d cross = dirs[prim_dir].Cross(residualMatrix.getCol(i)); + if (cross.IsNull()) { + continue; } + cross.Normalize(); + int last_dir = 3 - i - prim_dir; + if (i - prim_dir == 1) { + dirs[last_dir] = cross; + dirs[i] = cross.Cross(dirs[prim_dir]); + } + else { + dirs[last_dir] = -cross; + dirs[i] = dirs[prim_dir].Cross(-cross); + } + prim_dir = -2; // done + break; } if (prim_dir >= 0) { // handle case with only one valid direction @@ -1025,13 +1025,13 @@ std::array Matrix4D::decompose() const scaleMatrix.dMtrx4D[1][1] = yScale; scaleMatrix.dMtrx4D[2][2] = zScale; // The remaining shear - residualMatrix.scale(xScale ? 1.0 / xScale : 1.0, - yScale ? 1.0 / yScale : 1.0, - zScale ? 1.0 / zScale : 1.0); + residualMatrix.scale(xScale != 0 ? 1.0 / xScale : 1.0, + yScale != 0 ? 1.0 / yScale : 1.0, + zScale != 0 ? 1.0 / zScale : 1.0); // Restore trace in shear matrix residualMatrix.setDiagonal(Vector3d(1.0, 1.0, 1.0)); // Remove values close to zero - for (i = 0; i < 3; i++) { + for (int i = 0; i < 3; i++) { if (std::abs(scaleMatrix.dMtrx4D[i][i]) < 1e-15) { scaleMatrix.dMtrx4D[i][i] = 0.0; } diff --git a/src/Base/Matrix.h b/src/Base/Matrix.h index c74eb1a147..d8487fe7d2 100644 --- a/src/Base/Matrix.h +++ b/src/Base/Matrix.h @@ -98,8 +98,8 @@ public: inline Vector3d operator*(const Vector3d& vec) const; inline void multVec(const Vector3d& src, Vector3d& dst) const; inline void multVec(const Vector3f& src, Vector3f& dst) const; - inline Matrix4D operator*(double) const; - inline Matrix4D& operator*=(double); + inline Matrix4D operator*(double scalar) const; + inline Matrix4D& operator*=(double scalar); /// Comparison inline bool operator!=(const Matrix4D& mat) const; /// Comparison @@ -119,11 +119,11 @@ public: /// Get trace of the 4x4 matrix inline double trace() const; /// Set row to vector - inline void setRow(unsigned short usNdx, const Vector3d&); + inline void setRow(unsigned short usNdx, const Vector3d& vec); /// Set column to vector - inline void setCol(unsigned short usNdx, const Vector3d&); + inline void setCol(unsigned short usNdx, const Vector3d& vec); /// Set diagonal to vector - inline void setDiagonal(const Vector3d&); + inline void setDiagonal(const Vector3d& vec); /// Compute the determinant of the matrix double determinant() const; /// Compute the determinant of the 3x3 sub-matrix @@ -320,6 +320,10 @@ inline Matrix4D Matrix4D::operator*(const Matrix4D& mat) const inline Matrix4D& Matrix4D::operator=(const Matrix4D& mat) { + if (this == &mat) { + return *this; + } + for (int iz = 0; iz < 4; iz++) { for (int is = 0; is < 4; is++) { dMtrx4D[iz][is] = mat.dMtrx4D[iz][is]; diff --git a/src/Base/MatrixPyImp.cpp b/src/Base/MatrixPyImp.cpp index b3a46aba52..8d0229b0ec 100644 --- a/src/Base/MatrixPyImp.cpp +++ b/src/Base/MatrixPyImp.cpp @@ -52,7 +52,7 @@ std::string MatrixPy::representation() const return str.str(); } -PyObject* MatrixPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper +PyObject* MatrixPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { // create a new instance of MatrixPy and the Twin object return new MatrixPy(new Matrix4D); @@ -61,10 +61,12 @@ PyObject* MatrixPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python // constructor method int MatrixPy::PyInit(PyObject* args, PyObject* /*kwd*/) { + // NOLINTBEGIN double a11 = 1.0, a12 = 0.0, a13 = 0.0, a14 = 0.0; double a21 = 0.0, a22 = 1.0, a23 = 0.0, a24 = 0.0; double a31 = 0.0, a32 = 0.0, a33 = 1.0, a34 = 0.0; double a41 = 0.0, a42 = 0.0, a43 = 0.0, a44 = 1.0; + // NOLINTEND // clang-format off if (PyArg_ParseTuple(args, @@ -244,16 +246,15 @@ PyObject* MatrixPy::richCompare(PyObject* v, PyObject* w, int op) PyErr_SetString(PyExc_TypeError, "no ordering relation is defined for Matrix"); return nullptr; } - else if (op == Py_EQ) { + if (op == Py_EQ) { res = (m1 == m2) ? Py_True : Py_False; // NOLINT Py_INCREF(res); return res; } - else { - res = (m1 != m2) ? Py_True : Py_False; // NOLINT - Py_INCREF(res); - return res; - } + + res = (m1 != m2) ? Py_True : Py_False; // NOLINT + Py_INCREF(res); + return res; } else { // This always returns False @@ -264,7 +265,9 @@ PyObject* MatrixPy::richCompare(PyObject* v, PyObject* w, int op) PyObject* MatrixPy::move(PyObject* args) { - double x {}, y {}, z {}; + double x {}; + double y {}; + double z {}; Base::Vector3d vec; PyObject* pcVecObj {}; @@ -305,7 +308,9 @@ PyObject* MatrixPy::move(PyObject* args) PyObject* MatrixPy::scale(PyObject* args) { - double x {}, y {}, z {}; + double x {}; + double y {}; + double z {}; Base::Vector3d vec; PyObject* pcVecObj {}; @@ -426,7 +431,8 @@ PyObject* MatrixPy::transform(PyObject* args) { Base::Vector3d vec; Matrix4D mat; - PyObject *pcVecObj {}, *pcMatObj {}; + PyObject* pcVecObj {}; + PyObject* pcMatObj {}; if (!PyArg_ParseTuple( args, @@ -667,10 +673,9 @@ PyObject* MatrixPy::invert() getMatrixPtr()->inverseGauss(); Py_Return; } - else { - PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot invert singular matrix"); - return nullptr; - } + + PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot invert singular matrix"); + return nullptr; } PY_CATCH; } @@ -684,10 +689,9 @@ PyObject* MatrixPy::inverse() m.inverseGauss(); return new MatrixPy(m); } - else { - PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot invert singular matrix"); - return nullptr; - } + + PyErr_SetString(Base::PyExc_FC_GeneralError, "Cannot invert singular matrix"); + return nullptr; } PY_CATCH; } diff --git a/src/Base/Observer.h b/src/Base/Observer.h index 92220939db..a45fea156c 100644 --- a/src/Base/Observer.h +++ b/src/Base/Observer.h @@ -46,7 +46,7 @@ class Subject; * Attach itself to the observed object. * @see FCSubject */ -template +template class Observer { public: @@ -69,14 +69,14 @@ public: * @param rcReason * \todo undocumented parameter 2 */ - virtual void OnChange(Subject<_MessageType>& rCaller, _MessageType rcReason) = 0; + virtual void OnChange(Subject& rCaller, MsgType rcReason) = 0; /** * This method need to be reimplemented from the concrete Observer * and get called by the observed class * @param rCaller a reference to the calling object */ - virtual void OnDestroy(Subject<_MessageType>& rCaller) + virtual void OnDestroy(Subject& rCaller) { (void)rCaller; } @@ -90,6 +90,9 @@ public: { return nullptr; } + +protected: + FC_DEFAULT_COPY_MOVE(Observer) }; /** Subject class @@ -99,13 +102,13 @@ public: * Attach itself to the observed object. * @see FCObserver */ -template +template class Subject { public: - using ObserverType = Observer<_MessageType>; - using MessageType = _MessageType; - using SubjectType = Subject<_MessageType>; + using ObserverType = Observer; + using MessageType = MsgType; + using SubjectType = Subject; /** * A constructor. @@ -131,7 +134,7 @@ public: * @param ToObserv A pointer to a concrete Observer * @see Notify */ - void Attach(Observer<_MessageType>* ToObserv) + void Attach(Observer* ToObserv) { #ifdef FC_DEBUG size_t count = _ObserverSet.size(); @@ -152,7 +155,7 @@ public: * @param ToObserv A pointer to a concrete Observer * @see Notify */ - void Detach(Observer<_MessageType>* ToObserv) + void Detach(Observer* ToObserv) { #ifdef FC_DEBUG size_t count = _ObserverSet.size(); @@ -173,9 +176,9 @@ public: * Oberserver and Subject. * @see Notify */ - void Notify(_MessageType rcReason) + void Notify(MsgType rcReason) { - for (typename std::set*>::iterator Iter = _ObserverSet.begin(); + for (typename std::set*>::iterator Iter = _ObserverSet.begin(); Iter != _ObserverSet.end(); ++Iter) { try { @@ -202,10 +205,10 @@ public: * Get a observer by name if the observer reimplements the Name() mthode. * @see Observer */ - Observer<_MessageType>* Get(const char* Name) + Observer* Get(const char* Name) { const char* OName = nullptr; - for (typename std::set*>::iterator Iter = _ObserverSet.begin(); + for (typename std::set*>::iterator Iter = _ObserverSet.begin(); Iter != _ObserverSet.end(); ++Iter) { OName = (*Iter)->Name(); // get the name @@ -225,10 +228,12 @@ public: _ObserverSet.clear(); } - protected: + FC_DEFAULT_COPY_MOVE(Subject) + +private: /// Vector of attached observers - std::set*> _ObserverSet; + std::set*> _ObserverSet; }; // Workaround for MSVC diff --git a/src/Base/Parameter.cpp b/src/Base/Parameter.cpp index 6e671273de..47163d7259 100644 --- a/src/Base/Parameter.cpp +++ b/src/Base/Parameter.cpp @@ -25,6 +25,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ +#include #include #include #include @@ -75,14 +76,6 @@ using namespace Base; class DOMTreeErrorReporter: public ErrorHandler { public: - // ----------------------------------------------------------------------- - // Constructors and Destructor - // ----------------------------------------------------------------------- - DOMTreeErrorReporter() = default; - - ~DOMTreeErrorReporter() override = default; - - // ----------------------------------------------------------------------- // Implementation of the error handler interface // ----------------------------------------------------------------------- @@ -120,7 +113,7 @@ public: //@{ /** @ interface from DOMWriterFilter */ - FilterAction acceptNode(const XERCES_CPP_NAMESPACE_QUALIFIER DOMNode*) const override; + FilterAction acceptNode(const XERCES_CPP_NAMESPACE_QUALIFIER DOMNode* node) const override; //@{ ShowType getWhatToShow() const override @@ -130,10 +123,13 @@ public: // unimplemented copy ctor and assignment operator DOMPrintFilter(const DOMPrintFilter&) = delete; + DOMPrintFilter(DOMPrintFilter&&) = delete; DOMPrintFilter& operator=(const DOMPrintFilter&) = delete; + DOMPrintFilter& operator=(DOMPrintFilter&&) = delete; ShowType fWhatToShow; }; + class DOMPrintErrorHandler: public DOMErrorHandler { public: @@ -146,8 +142,10 @@ public: {} /* Unimplemented constructors and operators */ - explicit DOMPrintErrorHandler(const DOMErrorHandler&) = delete; - void operator=(const DOMErrorHandler&) = delete; + DOMPrintErrorHandler(const DOMPrintErrorHandler&) = delete; + DOMPrintErrorHandler(DOMPrintErrorHandler&&) = delete; + void operator=(const DOMPrintErrorHandler&) = delete; + void operator=(DOMPrintErrorHandler&&) = delete; }; @@ -464,7 +462,7 @@ std::string ParameterGrp::GetPath() const if (_Parent && _Parent != _Manager) { path = _Parent->GetPath(); } - if (path.size() && _cName.size()) { + if (!path.empty() && !_cName.empty()) { path += "/"; } path += _cName; @@ -506,9 +504,8 @@ bool ParameterGrp::IsEmpty() const if (_pGroupNode && _pGroupNode->getFirstChild()) { return false; } - else { - return true; - } + + return true; } /// test if a special sub group is in this group @@ -730,13 +727,9 @@ bool ParameterGrp::GetBool(const char* Name, bool bPreset) const if (!pcElem) { return bPreset; } + // if yes check the value and return - if (strcmp(StrX(pcElem->getAttribute(XStr("Value").unicodeForm())).c_str(), "1")) { - return false; - } - else { - return true; - } + return (strcmp(StrX(pcElem->getAttribute(XStr("Value").unicodeForm())).c_str(), "1") == 0); } void ParameterGrp::SetBool(const char* Name, bool bValue) @@ -758,7 +751,7 @@ std::vector ParameterGrp::GetBools(const char* sFilter) const Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { - if (strcmp(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(), "1")) { + if (strcmp(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(), "1") != 0) { vrValues.push_back(false); } else { @@ -785,7 +778,7 @@ std::vector> ParameterGrp::GetBoolMap(const char* s Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition if (!sFilter || Name.find(sFilter) != std::string::npos) { - if (strcmp(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(), "1")) { + if (strcmp(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(), "1") != 0) { vrValues.emplace_back(Name, false); } else { @@ -1381,13 +1374,10 @@ bool ParameterGrp::ShouldRemove() const if (this->getRefCount() > 1) { return false; } - for (const auto& it : _GroupMap) { - bool ok = it.second->ShouldRemove(); - if (!ok) { - return false; - } - } - return true; + + return std::all_of(_GroupMap.cbegin(), _GroupMap.cend(), [](const auto& it) { + return it.second->ShouldRemove(); + }); } XERCES_CPP_NAMESPACE_QUALIFIER DOMElement* @@ -1710,9 +1700,8 @@ int ParameterManager::LoadDocument() if (paramSerializer) { return paramSerializer->LoadDocument(*this); } - else { - return -1; - } + + return -1; } bool ParameterManager::LoadOrCreateDocument() @@ -1720,9 +1709,8 @@ bool ParameterManager::LoadOrCreateDocument() if (paramSerializer) { return paramSerializer->LoadOrCreateDocument(*this); } - else { - return false; - } + + return false; } void ParameterManager::SaveDocument() const @@ -1742,10 +1730,9 @@ bool ParameterManager::LoadOrCreateDocument(const char* sFileName) LoadDocument(sFileName); return false; } - else { - CreateDocument(); - return true; - } + + CreateDocument(); + return true; } int ParameterManager::LoadDocument(const char* sFileName) @@ -2017,7 +2004,7 @@ void ParameterManager::CheckDocument() const // DOMTreeErrorReporter //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void DOMTreeErrorReporter::warning(const SAXParseException&) +void DOMTreeErrorReporter::warning(const SAXParseException& /*exc*/) { // // Ignore all warnings. diff --git a/src/Base/Parameter.h b/src/Base/Parameter.h index 4a68318460..374a4d0980 100644 --- a/src/Base/Parameter.h +++ b/src/Base/Parameter.h @@ -29,8 +29,8 @@ * 3rd party Xerces-C++ XML parser is used to parse and write the XML. */ -#ifndef BASE__PARAMETER_H -#define BASE__PARAMETER_H +#ifndef BASE_PARAMETER_H +#define BASE_PARAMETER_H // Python stuff using PyObject = struct _object; @@ -94,6 +94,11 @@ class ParameterManager; class BaseExport ParameterGrp: public Base::Handled, public Base::Subject { public: + ParameterGrp(const ParameterGrp&) = delete; + ParameterGrp(ParameterGrp&&) = delete; + ParameterGrp& operator=(const ParameterGrp&) = delete; + ParameterGrp& operator=(ParameterGrp&&) = delete; + /** @name copy and insertation */ //@{ /// make a deep copy to the other group @@ -346,7 +351,9 @@ protected: class BaseExport ParameterSerializer { public: - ParameterSerializer(const std::string& fn); + explicit ParameterSerializer(const std::string& fn); + ParameterSerializer(const ParameterSerializer&) = delete; + ParameterSerializer(ParameterSerializer&&) = delete; virtual ~ParameterSerializer(); virtual void SaveDocument(const ParameterManager&); @@ -357,7 +364,10 @@ public: return filename; } -protected: + ParameterSerializer& operator=(const ParameterSerializer&) = delete; + ParameterSerializer& operator=(ParameterSerializer&&) = delete; + +private: std::string filename; }; @@ -446,7 +456,14 @@ private: private: ParameterManager(); + +public: ~ParameterManager() override; + ParameterManager(const ParameterManager&) = delete; + ParameterManager(ParameterManager&&) = delete; + + ParameterManager& operator=(const ParameterManager&) = delete; + ParameterManager& operator=(ParameterManager&&) = delete; }; /** python wrapper function @@ -454,4 +471,4 @@ private: BaseExport PyObject* GetPyObject(const Base::Reference& hcParamGrp); -#endif // BASE__PARAMETER_H +#endif // BASE_PARAMETER_H diff --git a/src/Base/ParameterPy.cpp b/src/Base/ParameterPy.cpp index d17c816e2a..f6ea8d797c 100644 --- a/src/Base/ParameterPy.cpp +++ b/src/Base/ParameterPy.cpp @@ -46,7 +46,7 @@ namespace Base { -class ParameterGrpObserver: public ParameterGrp::ObserverType +class ParameterGrpObserver: public ParameterGrp::ObserverType // NOLINT { public: explicit ParameterGrpObserver(const Py::Object& obj) @@ -100,7 +100,7 @@ private: using ParameterGrpObserverList = std::list; -class ParameterGrpPy: public Py::PythonExtension +class ParameterGrpPy: public Py::PythonExtension // NOLINT { public: static void init_type(); // announce properties and methods @@ -251,11 +251,15 @@ ParameterGrpPy::ParameterGrpPy(const Base::Reference& rcParamGrp) ParameterGrpPy::~ParameterGrpPy() { - for (ParameterGrpObserver* obs : _observers) { - if (!obs->_target) { - _cParamGrp->Detach(obs); + try { + for (ParameterGrpObserver* obs : _observers) { + if (!obs->_target) { + _cParamGrp->Detach(obs); + } + delete obs; } - delete obs; + } + catch (...) { } } @@ -263,7 +267,7 @@ Py::Object ParameterGrpPy::repr() { std::stringstream s; s << ""; - return Py::String(s.str()); + return Py::String(s.str()); // NOLINT } Py::Object ParameterGrpPy::importFrom(const Py::Tuple& args) @@ -315,9 +319,8 @@ Py::Object ParameterGrpPy::getGroup(const Py::Tuple& args) // increment the ref count return Py::asObject(pcParamGrp); } - else { - throw Py::RuntimeError("GetGroup failed"); - } + + throw Py::RuntimeError("GetGroup failed"); } catch (const Base::Exception& e) { e.setPyException(); @@ -369,7 +372,7 @@ Py::Object ParameterGrpPy::getGroupName(const Py::Tuple& args) // get the Handle of the wanted group std::string name = _cParamGrp->GetGroupName(); - return Py::String(name); + return Py::String(name); // NOLINT } Py::Object ParameterGrpPy::getGroups(const Py::Tuple& args) @@ -385,7 +388,7 @@ Py::Object ParameterGrpPy::getGroups(const Py::Tuple& args) list.append(Py::String(it->GetGroupName())); } - return list; + return list; // NOLINT } Py::Object ParameterGrpPy::setBool(const Py::Tuple& args) @@ -408,7 +411,7 @@ Py::Object ParameterGrpPy::getBool(const Py::Tuple& args) throw Py::Exception(); } - return Py::Boolean(_cParamGrp->GetBool(pstr, Bool != 0)); + return Py::Boolean(_cParamGrp->GetBool(pstr, Bool != 0)); // NOLINT } Py::Object ParameterGrpPy::getBools(const Py::Tuple& args) @@ -424,7 +427,7 @@ Py::Object ParameterGrpPy::getBools(const Py::Tuple& args) list.append(Py::String(it.first)); } - return list; + return list; // NOLINT } Py::Object ParameterGrpPy::setInt(const Py::Tuple& args) @@ -446,7 +449,7 @@ Py::Object ParameterGrpPy::getInt(const Py::Tuple& args) if (!PyArg_ParseTuple(args.ptr(), "s|i", &pstr, &Int)) { throw Py::Exception(); } - return Py::Long(_cParamGrp->GetInt(pstr, Int)); + return Py::Long(_cParamGrp->GetInt(pstr, Int)); // NOLINT } Py::Object ParameterGrpPy::getInts(const Py::Tuple& args) @@ -462,7 +465,7 @@ Py::Object ParameterGrpPy::getInts(const Py::Tuple& args) list.append(Py::String(it.first)); } - return list; + return list; // NOLINT } Py::Object ParameterGrpPy::setUnsigned(const Py::Tuple& args) @@ -484,7 +487,7 @@ Py::Object ParameterGrpPy::getUnsigned(const Py::Tuple& args) if (!PyArg_ParseTuple(args.ptr(), "s|I", &pstr, &UInt)) { throw Py::Exception(); } - return Py::Long(_cParamGrp->GetUnsigned(pstr, UInt)); + return Py::Long(_cParamGrp->GetUnsigned(pstr, UInt)); // NOLINT } Py::Object ParameterGrpPy::getUnsigneds(const Py::Tuple& args) @@ -500,7 +503,7 @@ Py::Object ParameterGrpPy::getUnsigneds(const Py::Tuple& args) list.append(Py::String(it.first)); } - return list; + return list; // NOLINT } Py::Object ParameterGrpPy::setFloat(const Py::Tuple& args) @@ -523,7 +526,7 @@ Py::Object ParameterGrpPy::getFloat(const Py::Tuple& args) throw Py::Exception(); } - return Py::Float(_cParamGrp->GetFloat(pstr, Float)); + return Py::Float(_cParamGrp->GetFloat(pstr, Float)); // NOLINT } Py::Object ParameterGrpPy::getFloats(const Py::Tuple& args) @@ -539,7 +542,7 @@ Py::Object ParameterGrpPy::getFloats(const Py::Tuple& args) list.append(Py::String(it.first)); } - return list; + return list; // NOLINT } Py::Object ParameterGrpPy::setString(const Py::Tuple& args) @@ -562,7 +565,7 @@ Py::Object ParameterGrpPy::getString(const Py::Tuple& args) throw Py::Exception(); } - return Py::String(_cParamGrp->GetASCII(pstr, str)); + return Py::String(_cParamGrp->GetASCII(pstr, str)); // NOLINT } Py::Object ParameterGrpPy::getStrings(const Py::Tuple& args) @@ -578,7 +581,7 @@ Py::Object ParameterGrpPy::getStrings(const Py::Tuple& args) list.append(Py::String(it.first)); } - return list; + return list; // NOLINT } Py::Object ParameterGrpPy::remInt(const Py::Tuple& args) @@ -663,7 +666,7 @@ Py::Object ParameterGrpPy::isEmpty(const Py::Tuple& args) throw Py::Exception(); } - return Py::Boolean(_cParamGrp->IsEmpty()); + return Py::Boolean(_cParamGrp->IsEmpty()); // NOLINT } Py::Object ParameterGrpPy::hasGroup(const Py::Tuple& args) @@ -673,7 +676,7 @@ Py::Object ParameterGrpPy::hasGroup(const Py::Tuple& args) throw Py::Exception(); } - return Py::Boolean(_cParamGrp->HasGroup(pstr)); + return Py::Boolean(_cParamGrp->HasGroup(pstr)); // NOLINT } Py::Object ParameterGrpPy::attach(const Py::Tuple& args) @@ -867,7 +870,7 @@ Py::Object ParameterGrpPy::getContents(const Py::Tuple& args) list.append(t6); } - return list; + return list; // NOLINT } } // namespace Base diff --git a/src/Base/PersistencePyImp.cpp b/src/Base/PersistencePyImp.cpp index 4f5cbf962b..3c9f72d323 100644 --- a/src/Base/PersistencePyImp.cpp +++ b/src/Base/PersistencePyImp.cpp @@ -83,13 +83,13 @@ PyObject* PersistencePy::dumpContent(PyObject* args, PyObject* kwds) } // build the byte array with correct size - if (!stream.seekp(0, stream.end)) { + if (!stream.seekp(0, std::stringstream::end)) { PyErr_SetString(PyExc_IOError, "Unable to find end of stream"); return nullptr; } std::stringstream::pos_type offset = stream.tellp(); - if (!stream.seekg(0, stream.beg)) { + if (!stream.seekg(0, std::stringstream::beg)) { PyErr_SetString(PyExc_IOError, "Unable to find begin of stream"); return nullptr; } diff --git a/src/Base/PlacementPyImp.cpp b/src/Base/PlacementPyImp.cpp index b2d34a6865..fb5367b591 100644 --- a/src/Base/PlacementPyImp.cpp +++ b/src/Base/PlacementPyImp.cpp @@ -40,7 +40,9 @@ using namespace Base; // returns a string which represents the object e.g. when printed in python std::string PlacementPy::representation() const { - double yaw {}, pitch {}, roll {}; + double yaw {}; + double pitch {}; + double roll {}; PlacementPy::PointerType ptr = getPlacementPtr(); std::stringstream str; ptr->getRotation().getYawPitchRoll(yaw, pitch, roll); @@ -52,7 +54,7 @@ std::string PlacementPy::representation() const return str.str(); } -PyObject* PlacementPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper +PyObject* PlacementPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { // create a new instance of PlacementPy and the Twin object return new PlacementPy(new Placement); @@ -398,7 +400,8 @@ PyObject* PlacementPy::getCustomAttributes(const char* attr) const { // for backward compatibility if (strcmp(attr, "isNull") == 0) { - PyObject *w {}, *res {}; + PyObject* w {}; + PyObject* res {}; w = PyUnicode_InternFromString("isIdentity"); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) res = PyObject_GenericGetAttr(const_cast(this), w); diff --git a/src/Base/Precision.h b/src/Base/Precision.h index a65ff5f7fc..8c7fbee348 100644 --- a/src/Base/Precision.h +++ b/src/Base/Precision.h @@ -187,7 +187,7 @@ public: * \param R * \return */ - static double IsInfinite(const double R) + static bool IsInfinite(const double R) { return std::fabs(R) >= (0.5 * Precision::Infinite()); } @@ -198,7 +198,7 @@ public: * \param R * \return */ - static double IsPositiveInfinite(const double R) + static bool IsPositiveInfinite(const double R) { return R >= (0.5 * Precision::Infinite()); } diff --git a/src/Base/ProgressIndicatorPy.cpp b/src/Base/ProgressIndicatorPy.cpp index 65346ca330..fffed5ff2e 100644 --- a/src/Base/ProgressIndicatorPy.cpp +++ b/src/Base/ProgressIndicatorPy.cpp @@ -53,12 +53,13 @@ PyTypeObject* ProgressIndicatorPy::type_object() return Py::PythonExtension::type_object(); } -bool ProgressIndicatorPy::check(PyObject* p) +bool ProgressIndicatorPy::check(PyObject* py) { - return Py::PythonExtension::check(p); + return Py::PythonExtension::check(py); } -PyObject* ProgressIndicatorPy::PyMake(struct _typeobject*, PyObject*, PyObject*) +PyObject* +ProgressIndicatorPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { return new ProgressIndicatorPy(); } @@ -80,7 +81,7 @@ Py::Object ProgressIndicatorPy::start(const Py::Tuple& args) if (!PyArg_ParseTuple(args.ptr(), "sI", &text, &steps)) { throw Py::Exception(); } - if (!_seq.get()) { + if (!_seq) { _seq = std::make_unique(text, steps); } return Py::None(); @@ -92,9 +93,9 @@ Py::Object ProgressIndicatorPy::next(const Py::Tuple& args) if (!PyArg_ParseTuple(args.ptr(), "|i", &b)) { throw Py::Exception(); } - if (_seq.get()) { + if (_seq) { try { - _seq->next(b ? true : false); + _seq->next(b != 0); } catch (const Base::AbortException&) { _seq.reset(); diff --git a/src/Base/ProgressIndicatorPy.h b/src/Base/ProgressIndicatorPy.h index 1b14ee8431..42c1491741 100644 --- a/src/Base/ProgressIndicatorPy.h +++ b/src/Base/ProgressIndicatorPy.h @@ -37,7 +37,7 @@ public: static void init_type(); // announce properties and methods static Py::PythonType& behaviors(); static PyTypeObject* type_object(); - static bool check(PyObject* p); + static bool check(PyObject* py); ProgressIndicatorPy(); ~ProgressIndicatorPy() override; diff --git a/src/Base/PyObjectBase.cpp b/src/Base/PyObjectBase.cpp index 3d2e0d3f61..4f00c0b4ae 100644 --- a/src/Base/PyObjectBase.cpp +++ b/src/Base/PyObjectBase.cpp @@ -80,8 +80,9 @@ PyObjectBase::~PyObjectBase() Base::Console().Log("PyO-: %s (%p)\n",Py_TYPE(this)->tp_name, this); #endif // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - if (baseProxy && reinterpret_cast(baseProxy)->baseobject == this) + if (baseProxy && reinterpret_cast(baseProxy)->baseobject == this) { Py_DECREF(baseProxy); + } Py_XDECREF(attrDict); } @@ -108,8 +109,9 @@ PyBaseProxy_dealloc(PyObject* self) { /* Clear weakrefs first before calling any destructors */ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - if (reinterpret_cast(self)->weakreflist) + if (reinterpret_cast(self)->weakreflist) { PyObject_ClearWeakRefs(self); + } Py_TYPE(self)->tp_free(self); } @@ -249,8 +251,9 @@ PyObject* createWeakRef(PyObjectBase* ptr) static bool init = false; if (!init) { init = true; - if (PyType_Ready(&PyBaseProxyType) < 0) + if (PyType_Ready(&PyBaseProxyType) < 0) { return nullptr; + } } PyObject* proxy = ptr->baseProxy; @@ -295,8 +298,9 @@ PyObject* PyObjectBase::__getattro(PyObject * obj, PyObject *attro) // the wrong type object (#0003311) if (streq(attr, "__class__")) { PyObject* res = PyObject_GenericGetAttr(obj, attro); - if (res) + if (res) { return res; + } } // This should be the entry in Type @@ -416,7 +420,8 @@ PyObject *PyObjectBase::_getattr(const char *attr) } else { // As fallback solution use Python's default method to get generic attributes - PyObject *w{}, *res{}; + PyObject *w{}; + PyObject *res{}; w = PyUnicode_InternFromString(attr); if (w) { res = PyObject_GenericGetAttr(this, w); @@ -433,8 +438,9 @@ PyObject *PyObjectBase::_getattr(const char *attr) int PyObjectBase::_setattr(const char *attr, PyObject *value) { - if (streq(attr,"softspace")) + if (streq(attr,"softspace")) { return -1; // filter out softspace + } PyObject *w{}; // As fallback solution use Python's default method to get generic attributes w = PyUnicode_InternFromString(attr); // new reference @@ -504,8 +510,9 @@ void PyObjectBase::setAttributeOf(const char* attr, PyObject* par) void PyObjectBase::startNotify() { - if (!shouldNotify()) + if (!shouldNotify()) { return; + } if (attrDict) { // This is the attribute name to the parent structure @@ -529,8 +536,9 @@ void PyObjectBase::startNotify() Py_DECREF(attr); // might be destroyed now Py_DECREF(this); // might be destroyed now - if (PyErr_Occurred()) + if (PyErr_Occurred()) { PyErr_Clear(); + } } Py_DECREF(key1); Py_DECREF(key2); diff --git a/src/Base/PyObjectBase.h b/src/Base/PyObjectBase.h index 1a024c09a4..09e6b72055 100644 --- a/src/Base/PyObjectBase.h +++ b/src/Base/PyObjectBase.h @@ -24,6 +24,7 @@ #define BASE_PYOBJECTBASE_H // clang-format off +// NOLINTBEGIN(cppcoreguidelines-macro-usage) // Std. configurations // (re-)defined in pyconfig.h @@ -511,8 +512,9 @@ inline PyObject * PyAsUnicodeObject(const char *str) // Returns a new reference, don't increment it! Py_ssize_t len = Py_SAFE_DOWNCAST(strlen(str), size_t, Py_ssize_t); PyObject *p = PyUnicode_DecodeUTF8(str, len, nullptr); - if (!p) + if (!p) { throw Base::UnicodeError("UTF8 conversion failure at PyAsUnicodeString()"); + } return p; } @@ -547,13 +549,15 @@ inline void PyTypeCheck(PyObject** ptr, int (*method)(PyObject*), const char* ms *ptr = nullptr; return; } - if (!method(*ptr)) + if (!method(*ptr)) { throw Base::TypeError(msg); + } } } // namespace Base +// NOLINTBEGIN(cppcoreguidelines-macro-usage) // clang-format on #endif // BASE_PYOBJECTBASE_H diff --git a/src/Base/QuantityPyImp.cpp b/src/Base/QuantityPyImp.cpp index e7b9c24fe0..6069342ebf 100644 --- a/src/Base/QuantityPyImp.cpp +++ b/src/Base/QuantityPyImp.cpp @@ -69,7 +69,7 @@ PyObject* QuantityPy::toStr(PyObject* args) return Py_BuildValue("s", ret.str().c_str()); } -PyObject* QuantityPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper +PyObject* QuantityPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { // create a new instance of QuantityPy and the Twin object return new QuantityPy(new Quantity); @@ -343,8 +343,10 @@ static Quantity& pyToQuantity(Quantity& q, PyObject* pyobj) PyObject* QuantityPy::number_add_handler(PyObject* self, PyObject* other) { - Quantity *pa = nullptr, *pb = nullptr; - Quantity a, b; + Quantity* pa = nullptr; + Quantity* pb = nullptr; + Quantity a; + Quantity b; PY_TRY { if (PyObject_TypeCheck(self, &(QuantityPy::Type))) { @@ -367,8 +369,10 @@ PyObject* QuantityPy::number_add_handler(PyObject* self, PyObject* other) PyObject* QuantityPy::number_subtract_handler(PyObject* self, PyObject* other) { - Quantity *pa = nullptr, *pb = nullptr; - Quantity a, b; + Quantity* pa = nullptr; + Quantity* pb = nullptr; + Quantity a; + Quantity b; PY_TRY { if (PyObject_TypeCheck(self, &(QuantityPy::Type))) { @@ -391,8 +395,10 @@ PyObject* QuantityPy::number_subtract_handler(PyObject* self, PyObject* other) PyObject* QuantityPy::number_multiply_handler(PyObject* self, PyObject* other) { - Quantity *pa = nullptr, *pb = nullptr; - Quantity a, b; + Quantity* pa = nullptr; + Quantity* pb = nullptr; + Quantity a; + Quantity b; PY_TRY { if (PyObject_TypeCheck(self, &(QuantityPy::Type))) { @@ -415,8 +421,10 @@ PyObject* QuantityPy::number_multiply_handler(PyObject* self, PyObject* other) PyObject* QuantityPy::number_divide_handler(PyObject* self, PyObject* other) { - Quantity *pa = nullptr, *pb = nullptr; - Quantity a, b; + Quantity* pa = nullptr; + Quantity* pb = nullptr; + Quantity a; + Quantity b; PY_TRY { if (PyObject_TypeCheck(self, &(QuantityPy::Type))) { @@ -444,7 +452,8 @@ PyObject* QuantityPy::number_remainder_handler(PyObject* self, PyObject* other) return nullptr; } - double d1 {}, d2 {}; + double d1 {}; + double d2 {}; Base::Quantity* a = static_cast(self)->getQuantityPtr(); d1 = a->getValue(); diff --git a/src/Base/Reader.cpp b/src/Base/Reader.cpp index d3036492a8..6b6068bf12 100644 --- a/src/Base/Reader.cpp +++ b/src/Base/Reader.cpp @@ -504,7 +504,7 @@ bool Base::XMLReader::isRegistered(Base::Persistence* Object) const return false; } -void Base::XMLReader::addName(const char*, const char*) +void Base::XMLReader::addName(const char* /*unused*/, const char* /*unused*/) {} const char* Base::XMLReader::getName(const char* name) const diff --git a/src/Base/Rotation.cpp b/src/Base/Rotation.cpp index b8f7516efc..f4f3197375 100644 --- a/src/Base/Rotation.cpp +++ b/src/Base/Rotation.cpp @@ -69,7 +69,7 @@ Rotation::Rotation(const double q[4]) * q0 = x, q1 = y, q2 = z and q3 = w, * where the quaternion is specified by q=w+xi+yj+zk. */ -Rotation::Rotation(const double q0, const double q1, const double q2, const double q3) +Rotation::Rotation(double q0, double q1, double q2, double q3) : Rotation() { this->setValue(q0, q1, q2, q3); @@ -81,33 +81,6 @@ Rotation::Rotation(const Vector3d& rotateFrom, const Vector3d& rotateTo) this->setValue(rotateFrom, rotateTo); } -Rotation::Rotation(const Rotation& rot) - : Rotation() -{ - this->quat[0] = rot.quat[0]; - this->quat[1] = rot.quat[1]; - this->quat[2] = rot.quat[2]; - this->quat[3] = rot.quat[3]; - - this->_axis[0] = rot._axis[0]; - this->_axis[1] = rot._axis[1]; - this->_axis[2] = rot._axis[2]; - this->_angle = rot._angle; -} - -void Rotation::operator=(const Rotation& rot) -{ - this->quat[0] = rot.quat[0]; - this->quat[1] = rot.quat[1]; - this->quat[2] = rot.quat[2]; - this->quat[3] = rot.quat[3]; - - this->_axis[0] = rot._axis[0]; - this->_axis[1] = rot._axis[1]; - this->_axis[2] = rot._axis[2]; - this->_angle = rot._angle; -} - const double* Rotation::getValue() const { return &this->quat[0]; @@ -146,7 +119,7 @@ void Rotation::evaluateVector() } } -void Rotation::setValue(const double q0, const double q1, const double q2, const double q3) +void Rotation::setValue(double q0, double q1, double q2, double q3) { this->quat[0] = q0; this->quat[1] = q1; @@ -258,7 +231,7 @@ void Rotation::setValue(const Matrix4D& m) this->evaluateVector(); } -void Rotation::setValue(const Vector3d& axis, const double fAngle) +void Rotation::setValue(const Vector3d& axis, double fAngle) { // Taken from // @@ -388,9 +361,16 @@ Rotation Rotation::operator*(const Rotation& q) const Rotation& Rotation::multRight(const Base::Rotation& q) { // Taken from - double x0 {}, y0 {}, z0 {}, w0 {}; + double x0 {}; + double y0 {}; + double z0 {}; + double w0 {}; this->getValue(x0, y0, z0, w0); - double x1 {}, y1 {}, z1 {}, w1 {}; + + double x1 {}; + double y1 {}; + double z1 {}; + double w1 {}; q.getValue(x1, y1, z1, w1); this->setValue(w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1, @@ -409,9 +389,16 @@ Rotation& Rotation::multRight(const Base::Rotation& q) Rotation& Rotation::multLeft(const Base::Rotation& q) { // Taken from - double x0 {}, y0 {}, z0 {}, w0 {}; + double x0 {}; + double y0 {}; + double z0 {}; + double w0 {}; q.getValue(x0, y0, z0, w0); - double x1 {}, y1 {}, z1 {}, w1 {}; + + double x1 {}; + double y1 {}; + double z1 {}; + double w1 {}; this->getValue(x1, y1, z1, w1); this->setValue(w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1, @@ -423,13 +410,7 @@ Rotation& Rotation::multLeft(const Base::Rotation& q) bool Rotation::operator==(const Rotation& q) const { - if ((this->quat[0] == q.quat[0] && this->quat[1] == q.quat[1] && this->quat[2] == q.quat[2] - && this->quat[3] == q.quat[3]) - || (this->quat[0] == -q.quat[0] && this->quat[1] == -q.quat[1] - && this->quat[2] == -q.quat[2] && this->quat[3] == -q.quat[3])) { - return true; - } - return false; + return isSame(q); } bool Rotation::operator!=(const Rotation& q) const @@ -591,9 +572,9 @@ Rotation::makeRotationByAxes(Vector3d xdir, Vector3d ydir, Vector3d zdir, const if (mainDir.Length() > tol) { break; } - else { - dropPriority(0); - } + + dropPriority(0); + if (i == 2) { THROWM(ValueError, "makeRotationByAxes: all directions supplied are zero"); } @@ -607,9 +588,9 @@ Rotation::makeRotationByAxes(Vector3d xdir, Vector3d ydir, Vector3d zdir, const if ((hintDir.Cross(mainDir)).Length() > tol) { break; } - else { - dropPriority(1); - } + + dropPriority(1); + if (i == 1) { hintDir = Vector3d(); // no vector can be used as hint direction. Zero it out, to // indicate that a guess is needed. @@ -757,13 +738,16 @@ void Rotation::getYawPitchRoll(double& y, double& p, double& r) const bool Rotation::isSame(const Rotation& q) const { - if ((this->quat[0] == q.quat[0] && this->quat[1] == q.quat[1] && this->quat[2] == q.quat[2] - && this->quat[3] == q.quat[3]) - || (this->quat[0] == -q.quat[0] && this->quat[1] == -q.quat[1] - && this->quat[2] == -q.quat[2] && this->quat[3] == -q.quat[3])) { - return true; - } - return false; + // clang-format off + return ((this->quat[0] == q.quat[0] && + this->quat[1] == q.quat[1] && + this->quat[2] == q.quat[2] && + this->quat[3] == q.quat[3]) || + (this->quat[0] == -q.quat[0] && + this->quat[1] == -q.quat[1] && + this->quat[2] == -q.quat[2] && + this->quat[3] == -q.quat[3])); + // clang-format on } bool Rotation::isSame(const Rotation& q, double tol) const @@ -992,7 +976,9 @@ void Rotation::setEulerAngles(EulerSequence theOrder, theBeta *= D_PI / 180.0; theGamma *= D_PI / 180.0; - double a = theAlpha, b = theBeta, c = theGamma; + double a = theAlpha; + double b = theBeta; + double c = theGamma; if (!o.isExtrinsic) { std::swap(a, c); } diff --git a/src/Base/Rotation.h b/src/Base/Rotation.h index edcdfec0db..f663c81510 100644 --- a/src/Base/Rotation.h +++ b/src/Base/Rotation.h @@ -41,19 +41,21 @@ public: /** Construction. */ //@{ Rotation(); - Rotation(const Vector3d& axis, const double fAngle); + Rotation(const Vector3d& axis, double fAngle); Rotation(const Matrix4D& matrix); Rotation(const double q[4]); - Rotation(const double q0, const double q1, const double q2, const double q3); + Rotation(double q0, double q1, double q2, double q3); Rotation(const Vector3d& rotateFrom, const Vector3d& rotateTo); - Rotation(const Rotation& rot); + Rotation(const Rotation& rot) = default; + Rotation(Rotation&& rot) = default; + ~Rotation() = default; //@} /** Methods to get or set rotations. */ //@{ const double* getValue() const; void getValue(double& q0, double& q1, double& q2, double& q3) const; - void setValue(const double q0, const double q1, const double q2, const double q3); + void setValue(double q0, double q1, double q2, double q3); /// If not a null quaternion then \a axis will be normalized void getValue(Vector3d& axis, double& rfAngle) const; /// Does the same as the method above unless normalizing the axis. @@ -61,7 +63,7 @@ public: void getValue(Matrix4D& matrix) const; void setValue(const double q[4]); void setValue(const Matrix4D& matrix); - void setValue(const Vector3d& axis, const double fAngle); + void setValue(const Vector3d& axis, double fAngle); void setValue(const Vector3d& rotateFrom, const Vector3d& rotateTo); /// Euler angles in yaw,pitch,roll notation void setYawPitchRoll(double y, double p, double r); @@ -112,8 +114,8 @@ public: }; static const char* eulerSequenceName(EulerSequence seq); static EulerSequence eulerSequenceFromName(const char* name); - void getEulerAngles(EulerSequence seq, double& alpha, double& beta, double& gamma) const; - void setEulerAngles(EulerSequence seq, double alpha, double beta, double gamma); + void getEulerAngles(EulerSequence theOrder, double& alpha, double& beta, double& gamma) const; + void setEulerAngles(EulerSequence theOrder, double alpha, double beta, double gamma); bool isIdentity() const; bool isIdentity(double tol) const; bool isNull() const; @@ -141,7 +143,8 @@ public: { return quat[usIndex]; } - void operator=(const Rotation&); + Rotation& operator=(const Rotation&) = default; + Rotation& operator=(Rotation&&) = default; Rotation& multRight(const Base::Rotation& q); Rotation& multLeft(const Base::Rotation& q); @@ -150,11 +153,11 @@ public: Vector3d multVec(const Vector3d& src) const; void multVec(const Vector3f& src, Vector3f& dst) const; Vector3f multVec(const Vector3f& src) const; - void scaleAngle(const double scaleFactor); + void scaleAngle(double scaleFactor); //@} /** Specialty constructors */ - static Rotation slerp(const Rotation& rot0, const Rotation& rot1, double t); + static Rotation slerp(const Rotation& q0, const Rotation& q1, double t); static Rotation identity(); /** diff --git a/src/Base/RotationPyImp.cpp b/src/Base/RotationPyImp.cpp index d9d7e9e10f..f4fac564e9 100644 --- a/src/Base/RotationPyImp.cpp +++ b/src/Base/RotationPyImp.cpp @@ -53,7 +53,7 @@ std::string RotationPy::representation() const return str.str(); } -PyObject* RotationPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper +PyObject* RotationPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { // create a new instance of RotationPy and the Twin object return new RotationPy(new Rotation); @@ -117,14 +117,19 @@ int RotationPy::PyInit(PyObject* args, PyObject* kwds) } PyErr_Clear(); - double q0 {}, q1 {}, q2 {}, q3 {}; + double q0 {}; + double q1 {}; + double q2 {}; + double q3 {}; if (PyArg_ParseTuple(args, "dddd", &q0, &q1, &q2, &q3)) { getRotationPtr()->setValue(q0, q1, q2, q3); return 0; } PyErr_Clear(); - double y {}, p {}, r {}; + double y {}; + double p {}; + double r {}; if (PyArg_ParseTuple(args, "ddd", &y, &p, &r)) { getRotationPtr()->setYawPitchRoll(y, p, r); return 0; @@ -132,7 +137,9 @@ int RotationPy::PyInit(PyObject* args, PyObject* kwds) PyErr_Clear(); const char* seq {}; - double a {}, b {}, c {}; + double a {}; + double b {}; + double c {}; if (PyArg_ParseTuple(args, "sddd", &seq, &a, &b, &c)) { PY_TRY { @@ -142,10 +149,12 @@ int RotationPy::PyInit(PyObject* args, PyObject* kwds) _PY_CATCH(return -1) } + // NOLINTBEGIN double a11 = 1.0, a12 = 0.0, a13 = 0.0, a14 = 0.0; double a21 = 0.0, a22 = 1.0, a23 = 0.0, a24 = 0.0; double a31 = 0.0, a32 = 0.0, a33 = 1.0, a34 = 0.0; double a41 = 0.0, a42 = 0.0, a43 = 0.0, a44 = 1.0; + // NOLINTEND // try read a 4x4 matrix PyErr_Clear(); @@ -190,7 +199,8 @@ int RotationPy::PyInit(PyObject* args, PyObject* kwds) } PyErr_Clear(); - PyObject *v1 {}, *v2 {}; + PyObject* v1 {}; + PyObject* v2 {}; if (PyArg_ParseTuple(args, "O!O!", &(Base::VectorPy::Type), &v1, @@ -333,7 +343,9 @@ PyObject* RotationPy::slerp(PyObject* args) PyObject* RotationPy::setYawPitchRoll(PyObject* args) { - double A {}, B {}, C {}; + double A {}; + double B {}; + double C {}; if (!PyArg_ParseTuple(args, "ddd", &A, &B, &C)) { return nullptr; } @@ -346,7 +358,9 @@ PyObject* RotationPy::getYawPitchRoll(PyObject* args) if (!PyArg_ParseTuple(args, "")) { return nullptr; } - double A {}, B {}, C {}; + double A {}; + double B {}; + double C {}; this->getRotationPtr()->getYawPitchRoll(A, B, C); Py::Tuple tuple(3); @@ -359,7 +373,9 @@ PyObject* RotationPy::getYawPitchRoll(PyObject* args) PyObject* RotationPy::setEulerAngles(PyObject* args) { const char* seq {}; - double A {}, B {}, C {}; + double A {}; + double B {}; + double C {}; if (!PyArg_ParseTuple(args, "sddd", &seq, &A, &B, &C)) { return nullptr; } @@ -390,7 +406,9 @@ PyObject* RotationPy::toEulerAngles(PyObject* args) PY_TRY { - double A {}, B {}, C {}; + double A {}; + double B {}; + double C {}; this->getRotationPtr()->getEulerAngles(Rotation::eulerSequenceFromName(seq), A, B, C); Py::Tuple tuple(3); @@ -446,7 +464,10 @@ PyObject* RotationPy::isNull(PyObject* args) Py::Tuple RotationPy::getQ() const { - double q0 {}, q1 {}, q2 {}, q3 {}; + double q0 {}; + double q1 {}; + double q2 {}; + double q3 {}; this->getRotationPtr()->getValue(q0, q1, q2, q3); Py::Tuple tuple(4); @@ -515,22 +536,28 @@ PyObject* RotationPy::getCustomAttributes(const char* attr) const this->getRotationPtr()->getValue(mat); return new MatrixPy(mat); } - else if (strcmp(attr, "Yaw") == 0) { - double A {}, B {}, C {}; + if (strcmp(attr, "Yaw") == 0) { + double A {}; + double B {}; + double C {}; this->getRotationPtr()->getYawPitchRoll(A, B, C); return PyFloat_FromDouble(A); } - else if (strcmp(attr, "Pitch") == 0) { - double A {}, B {}, C {}; + if (strcmp(attr, "Pitch") == 0) { + double A {}; + double B {}; + double C {}; this->getRotationPtr()->getYawPitchRoll(A, B, C); return PyFloat_FromDouble(B); } - else if (strcmp(attr, "Roll") == 0) { - double A {}, B {}, C {}; + if (strcmp(attr, "Roll") == 0) { + double A {}; + double B {}; + double C {}; this->getRotationPtr()->getYawPitchRoll(A, B, C); return PyFloat_FromDouble(C); } - else if (strcmp(attr, "toEuler") == 0) { + if (strcmp(attr, "toEuler") == 0) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) Py::Object self(const_cast(this), false); return Py::new_reference_to(self.getAttr("getYawPitchRoll")); @@ -567,7 +594,9 @@ int RotationPy::setCustomAttributes(const char* attr, PyObject* obj) else if (strcmp(attr, "Yaw") == 0) { if (PyNumber_Check(obj)) { double V = PyFloat_AsDouble(obj); - double A {}, B {}, C {}; + double A {}; + double B {}; + double C {}; this->getRotationPtr()->getYawPitchRoll(A, B, C); this->getRotationPtr()->setYawPitchRoll(V, B, C); return 1; @@ -576,7 +605,9 @@ int RotationPy::setCustomAttributes(const char* attr, PyObject* obj) else if (strcmp(attr, "Pitch") == 0) { if (PyNumber_Check(obj)) { double V = PyFloat_AsDouble(obj); - double A {}, B {}, C {}; + double A {}; + double B {}; + double C {}; this->getRotationPtr()->getYawPitchRoll(A, B, C); this->getRotationPtr()->setYawPitchRoll(A, V, C); return 1; @@ -585,7 +616,9 @@ int RotationPy::setCustomAttributes(const char* attr, PyObject* obj) else if (strcmp(attr, "Roll") == 0) { if (PyNumber_Check(obj)) { double V = PyFloat_AsDouble(obj); - double A {}, B {}, C {}; + double A {}; + double B {}; + double C {}; this->getRotationPtr()->getYawPitchRoll(A, B, C); this->getRotationPtr()->setYawPitchRoll(A, B, V); return 1; @@ -641,7 +674,7 @@ PyObject* RotationPy::number_power_handler(PyObject* self, PyObject* other, PyOb double rfAngle {}; a.getRawValue(axis, rfAngle); - rfAngle *= b; + rfAngle *= double(b); a.setValue(axis, rfAngle); return new RotationPy(a); diff --git a/src/Base/Sequencer.cpp b/src/Base/Sequencer.cpp index 15d140324f..4d41dc0009 100644 --- a/src/Base/Sequencer.cpp +++ b/src/Base/Sequencer.cpp @@ -44,14 +44,14 @@ struct SequencerP /** Sets a global sequencer object. * Access to the last registered object is performed by @see Sequencer(). */ - static void appendInstance(SequencerBase* s) + static void appendInstance(SequencerBase* sb) { - _instances.push_back(s); + _instances.push_back(sb); } - static void removeInstance(SequencerBase* s) + static void removeInstance(SequencerBase* sb) { std::vector::iterator it; - it = std::find(_instances.begin(), _instances.end(), s); + it = std::find(_instances.begin(), _instances.end(), sb); _instances.erase(it); } static SequencerBase& getInstance() @@ -72,7 +72,7 @@ QRecursiveMutex SequencerP::mutex; SequencerBase& SequencerBase::Instance() { // not initialized? - if (SequencerP::_instances.size() == 0) { + if (SequencerP::_instances.empty()) { new ConsoleSequencer(); } @@ -119,8 +119,8 @@ void SequencerBase::startStep() bool SequencerBase::next(bool canAbort) { this->nProgress++; - float fDiv = this->nTotalSteps > 0 ? static_cast(this->nTotalSteps) : 1000.0f; - int perc = int((float(this->nProgress) * (100.0f / fDiv))); + float fDiv = this->nTotalSteps > 0 ? static_cast(this->nTotalSteps) : 1000.0F; + int perc = int((float(this->nProgress) * (100.0F / fDiv))); // do only an update if we have increased by one percent if (perc > this->_nLastPercentage) { @@ -135,10 +135,10 @@ bool SequencerBase::next(bool canAbort) return this->nProgress < this->nTotalSteps; } -void SequencerBase::nextStep(bool) +void SequencerBase::nextStep(bool /*next*/) {} -void SequencerBase::setProgress(size_t) +void SequencerBase::setProgress(size_t /*value*/) {} bool SequencerBase::stop() @@ -204,7 +204,7 @@ void SequencerBase::resetData() this->_bCanceled = false; } -void SequencerBase::setText(const char*) +void SequencerBase::setText(const char* /*text*/) {} // --------------------------------------------------------- @@ -219,7 +219,7 @@ void ConsoleSequencer::setText(const char* pszTxt) void ConsoleSequencer::startStep() {} -void ConsoleSequencer::nextStep(bool) +void ConsoleSequencer::nextStep(bool /*canAbort*/) { if (this->nTotalSteps != 0) { printf("\t\t\t\t\t\t(%d %%)\t\r", progressInPercent()); diff --git a/src/Base/Sequencer.h b/src/Base/Sequencer.h index 72e39d98b7..f256832d93 100644 --- a/src/Base/Sequencer.h +++ b/src/Base/Sequencer.h @@ -126,6 +126,8 @@ public: * @see Sequencer */ static SequencerBase& Instance(); + /** Destruction */ + virtual ~SequencerBase(); /** * Returns true if the running sequencer is blocking any user input. * This might be only of interest of the GUI where the progress bar or dialog @@ -205,9 +207,9 @@ protected: /** construction */ SequencerBase(); SequencerBase(const SequencerBase&) = default; + SequencerBase(SequencerBase&&) = default; SequencerBase& operator=(const SequencerBase&) = default; - /** Destruction */ - virtual ~SequencerBase(); + SequencerBase& operator=(SequencerBase&&) = default; /** * Sets a text what the pending operation is doing. The default implementation * does nothing. @@ -375,7 +377,9 @@ public: bool wasCanceled() const; SequencerLauncher(const SequencerLauncher&) = delete; + SequencerLauncher(SequencerLauncher&&) = delete; void operator=(const SequencerLauncher&) = delete; + void operator=(SequencerLauncher&&) = delete; }; /** Access to the only SequencerBase instance */ diff --git a/src/Base/SmartPtrPy.cpp b/src/Base/SmartPtrPy.cpp index a0ac89435e..5041d230e9 100644 --- a/src/Base/SmartPtrPy.cpp +++ b/src/Base/SmartPtrPy.cpp @@ -117,10 +117,10 @@ bool SmartPtr::isNull() const return p == nullptr; } -BaseExport PyObject* new_reference_to(const SmartPtr& g) +BaseExport PyObject* new_reference_to(const SmartPtr& ptr) { - PyObject* p = g.ptr(); - Py::_XINCREF(p); - return p; + PyObject* py = ptr.ptr(); + Py::_XINCREF(py); + return py; } } // namespace Py diff --git a/src/Base/Stream.cpp b/src/Base/Stream.cpp index d32ff3df51..57d3efe630 100644 --- a/src/Base/Stream.cpp +++ b/src/Base/Stream.cpp @@ -602,7 +602,8 @@ PyStreambuf::int_type PyStreambuf::underflow() return traits_type::eof(); } - std::memcpy(start, &(c[0]), c.size()); + // Check: bugprone-not-null-terminated-result + std::memcpy(start, c.data(), c.size()); } catch (Py::Exception& e) { e.clear(); @@ -666,31 +667,29 @@ bool PyStreambuf::writeStr(const char* str, std::streamsize num) meth.apply(arg); return true; } - else if (type == BytesIO) { + if (type == BytesIO) { arg.setItem(0, Py::Bytes(str, num)); meth.apply(arg); return true; } - else { - // try out what works - try { - arg.setItem(0, Py::String(str, num)); + + // try out what works + try { + arg.setItem(0, Py::String(str, num)); + meth.apply(arg); + type = StringIO; + return true; + } + catch (Py::Exception& e) { + if (PyErr_ExceptionMatches(PyExc_TypeError)) { + e.clear(); + arg.setItem(0, Py::Bytes(str, num)); meth.apply(arg); - type = StringIO; + type = BytesIO; return true; } - catch (Py::Exception& e) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) { - e.clear(); - arg.setItem(0, Py::Bytes(str, num)); - meth.apply(arg); - type = BytesIO; - return true; - } - else { - throw; // re-throw - } - } + + throw; // re-throw } } catch (Py::Exception& e) { diff --git a/src/Base/Stream.h b/src/Base/Stream.h index e7664211a3..3db89acedf 100644 --- a/src/Base/Stream.h +++ b/src/Base/Stream.h @@ -154,12 +154,12 @@ public: ~ByteArrayOStreambuf() override; protected: - int_type overflow(std::streambuf::int_type v) override; + int_type overflow(std::streambuf::int_type c) override; std::streamsize xsputn(const char* s, std::streamsize num) override; pos_type seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode which = std::ios::in | std::ios::out) override; - pos_type seekpos(std::streambuf::pos_type sp, + pos_type seekpos(std::streambuf::pos_type pos, std::ios_base::openmode which = std::ios::in | std::ios::out) override; public: @@ -180,7 +180,7 @@ private: class BaseExport ByteArrayIStreambuf: public std::streambuf { public: - explicit ByteArrayIStreambuf(const QByteArray& buf); + explicit ByteArrayIStreambuf(const QByteArray& data); ~ByteArrayIStreambuf() override; protected: @@ -217,12 +217,12 @@ public: ~IODeviceOStreambuf() override; protected: - int_type overflow(std::streambuf::int_type v) override; + int_type overflow(std::streambuf::int_type c) override; std::streamsize xsputn(const char* s, std::streamsize num) override; pos_type seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode which = std::ios::in | std::ios::out) override; - pos_type seekpos(std::streambuf::pos_type sp, + pos_type seekpos(std::streambuf::pos_type pos, std::ios_base::openmode which = std::ios::in | std::ios::out) override; public: @@ -251,7 +251,7 @@ protected: pos_type seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode which = std::ios::in | std::ios::out) override; - pos_type seekpos(std::streambuf::pos_type sp, + pos_type seekpos(std::streambuf::pos_type pos, std::ios_base::openmode which = std::ios::in | std::ios::out) override; public: @@ -299,7 +299,7 @@ protected: int_type overflow(int_type c = EOF) override; std::streamsize xsputn(const char* s, std::streamsize num) override; int sync() override; - pos_type seekoff(off_type offset, seekdir dir, openmode) override; + pos_type seekoff(off_type offset, seekdir dir, openmode mode) override; pos_type seekpos(pos_type offset, openmode mode) override; private: diff --git a/src/Base/Swap.cpp b/src/Base/Swap.cpp index 26cdb337bb..41734b48b3 100644 --- a/src/Base/Swap.cpp +++ b/src/Base/Swap.cpp @@ -31,10 +31,10 @@ unsigned short Base::SwapOrder() return *((char*)&usDummy) == 1 ? LOW_ENDIAN : HIGH_ENDIAN; } -void Base::SwapVar(char&) +void Base::SwapVar(char& /*unused*/) {} -void Base::SwapVar(unsigned char&) +void Base::SwapVar(unsigned char& /*unused*/) {} void Base::SwapVar(short& s) diff --git a/src/Base/TimeInfo.cpp b/src/Base/TimeInfo.cpp index 8b14da8bd2..0fd6bb9fe9 100644 --- a/src/Base/TimeInfo.cpp +++ b/src/Base/TimeInfo.cpp @@ -58,16 +58,18 @@ TimeInfo::~TimeInfo() = default; void TimeInfo::setCurrent() { + // clang-format off #if defined(FC_OS_BSD) || defined(FC_OS_LINUX) || defined(__MINGW32__) - struct timeval t; - gettimeofday(&t, nullptr); - timebuffer.time = t.tv_sec; - timebuffer.millitm = t.tv_usec / 1000; + struct timeval tv {}; + gettimeofday(&tv, nullptr); + timebuffer.time = tv.tv_sec; + timebuffer.millitm = tv.tv_usec / 1000; #elif defined(FC_OS_WIN32) _ftime(&timebuffer); #else ftime(&timebuffer); // deprecated #endif + // clang-format on } void TimeInfo::setTime_t(int64_t seconds) @@ -95,7 +97,7 @@ float TimeInfo::diffTimeF(const TimeInfo& timeStart, const TimeInfo& timeEnd) int64_t ds = int64_t(timeEnd.getSeconds() - timeStart.getSeconds()); int dms = int(timeEnd.getMiliseconds()) - int(timeStart.getMiliseconds()); - return float(ds) + float(dms) * 0.001f; + return float(ds) + float(dms) * 0.001F; } TimeInfo TimeInfo::null() diff --git a/src/Base/TimeInfo.h b/src/Base/TimeInfo.h index 084dddd2f2..ae9164d41d 100644 --- a/src/Base/TimeInfo.h +++ b/src/Base/TimeInfo.h @@ -60,8 +60,9 @@ public: /// Construction TimeInfo(); TimeInfo(const TimeInfo&) = default; + TimeInfo(TimeInfo&&) = default; /// Destruction - virtual ~TimeInfo(); + ~TimeInfo(); /// sets the object to the actual system time void setCurrent(); @@ -70,7 +71,8 @@ public: int64_t getSeconds() const; unsigned short getMiliseconds() const; - void operator=(const TimeInfo& time); + TimeInfo& operator=(const TimeInfo& time) = default; + TimeInfo& operator=(TimeInfo&& time) = default; bool operator==(const TimeInfo& time) const; bool operator!=(const TimeInfo& time) const; @@ -85,12 +87,14 @@ public: bool isNull() const; static TimeInfo null(); -protected: +private: + // clang-format off #if defined(_MSC_VER) struct _timeb timebuffer; #elif defined(__GNUC__) - struct timeb timebuffer; + struct timeb timebuffer {}; #endif + // clang-format on }; @@ -110,11 +114,6 @@ inline bool TimeInfo::operator!=(const TimeInfo& time) const || timebuffer.millitm != time.timebuffer.millitm); } -inline void TimeInfo::operator=(const TimeInfo& time) -{ - timebuffer = time.timebuffer; -} - inline bool TimeInfo::operator==(const TimeInfo& time) const { return (timebuffer.time == time.timebuffer.time @@ -126,9 +125,7 @@ inline bool TimeInfo::operator<(const TimeInfo& time) const if (timebuffer.time == time.timebuffer.time) { return timebuffer.millitm < time.timebuffer.millitm; } - else { - return timebuffer.time < time.timebuffer.time; - } + return timebuffer.time < time.timebuffer.time; } inline bool TimeInfo::operator<=(const TimeInfo& time) const @@ -136,9 +133,7 @@ inline bool TimeInfo::operator<=(const TimeInfo& time) const if (timebuffer.time == time.timebuffer.time) { return timebuffer.millitm <= time.timebuffer.millitm; } - else { - return timebuffer.time <= time.timebuffer.time; - } + return timebuffer.time <= time.timebuffer.time; } inline bool TimeInfo::operator>=(const TimeInfo& time) const @@ -146,9 +141,7 @@ inline bool TimeInfo::operator>=(const TimeInfo& time) const if (timebuffer.time == time.timebuffer.time) { return timebuffer.millitm >= time.timebuffer.millitm; } - else { - return timebuffer.time >= time.timebuffer.time; - } + return timebuffer.time >= time.timebuffer.time; } inline bool TimeInfo::operator>(const TimeInfo& time) const @@ -156,9 +149,7 @@ inline bool TimeInfo::operator>(const TimeInfo& time) const if (timebuffer.time == time.timebuffer.time) { return timebuffer.millitm > time.timebuffer.millitm; } - else { - return timebuffer.time > time.timebuffer.time; - } + return timebuffer.time > time.timebuffer.time; } } // namespace Base diff --git a/src/Base/Tools.cpp b/src/Base/Tools.cpp index 224c123ba9..a764c0c5e8 100644 --- a/src/Base/Tools.cpp +++ b/src/Base/Tools.cpp @@ -43,12 +43,11 @@ struct string_comp if (s1.size() < s2.size()) { return true; } - else if (s1.size() > s2.size()) { + if (s1.size() > s2.size()) { return false; } - else { - return s1 < s2; - } + + return s1 < s2; } static std::string increment(const std::string& s) { @@ -105,7 +104,7 @@ private: for (const auto& name : names) { if (name.substr(0, base_name.length()) == base_name) { // same prefix std::string suffix(name.substr(base_name.length())); - if (suffix.size() > 0) { + if (!suffix.empty()) { std::string::size_type pos = suffix.find_first_not_of("0123456789"); if (pos == std::string::npos) { num_suffix = std::max(num_suffix, suffix, Base::string_comp()); diff --git a/src/Base/Tools.h b/src/Base/Tools.h index 2f637db067..194c92901b 100644 --- a/src/Base/Tools.h +++ b/src/Base/Tools.h @@ -116,9 +116,8 @@ inline T sgn(T t) if (t == 0) { return T(0); } - else { - return (t > 0) ? T(1) : T(-1); - } + + return (t > 0) ? T(1) : T(-1); } #ifndef M_PI @@ -157,6 +156,11 @@ public: int elapsed(); std::string toString(int ms) const; + StopWatch(const StopWatch&) = delete; + StopWatch(StopWatch&&) = delete; + StopWatch& operator=(const StopWatch&) = delete; + StopWatch& operator=(StopWatch&&) = delete; + private: struct Private; Private* d; diff --git a/src/Base/Tools2D.cpp b/src/Base/Tools2D.cpp index cc68068170..e9e39f8b02 100644 --- a/src/Base/Tools2D.cpp +++ b/src/Base/Tools2D.cpp @@ -24,6 +24,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ +#include #include #include #endif @@ -33,34 +34,33 @@ using namespace Base; -double Vector2d::GetAngle(const Vector2d& rclVect) const +double Vector2d::GetAngle(const Vector2d& vec) const { - double fDivid = 0.0, fNum = 0.0; + double fDivid = 0.0; + double fNum = 0.0; - fDivid = Length() * rclVect.Length(); + fDivid = Length() * vec.Length(); if ((fDivid < -1e-10) || (fDivid > 1e-10)) { - fNum = (*this * rclVect) / fDivid; + fNum = (*this * vec) / fDivid; if (fNum < -1) { return D_PI; } - else if (fNum > 1) { + if (fNum > 1) { return 0.0; } - else { - return acos(fNum); - } - } - else { - return -FLOAT_MAX; // division by zero + + return acos(fNum); } + + return -FLOAT_MAX; // division by zero } -void Vector2d::ProjectToLine(const Vector2d& rclPt, const Vector2d& rclLine) +void Vector2d::ProjectToLine(const Vector2d& point, const Vector2d& line) { - double l = rclLine.Length(); - double t1 = (rclPt * rclLine) / l; - Vector2d clNormal = rclLine; + double l = line.Length(); + double t1 = (point * line) / l; + Vector2d clNormal = line; clNormal.Normalize(); clNormal.Scale(t1); *this = clNormal; @@ -103,30 +103,20 @@ bool BoundBox2d::Intersect(const Line2d& rclLine) const clThisLine.clV1 = clThisLine.clV2; clThisLine.clV2.x = MinX; clThisLine.clV2.y = MinY; - if (clThisLine.IntersectAndContain(rclLine, clVct)) { - return true; - } - - return false; + return (clThisLine.IntersectAndContain(rclLine, clVct)); } bool BoundBox2d::Intersect(const BoundBox2d& rclBB) const { - if (MinX < rclBB.MaxX && rclBB.MinX < MaxX && MinY < rclBB.MaxY && rclBB.MinY < MaxY) { - return true; - } - else { // no intersection - return false; - } + return (MinX < rclBB.MaxX && rclBB.MinX < MaxX && MinY < rclBB.MaxY && rclBB.MinY < MaxY); } bool BoundBox2d::Intersect(const Polygon2d& rclPoly) const { - unsigned long i = 0; Line2d clLine; // points contained in boundbox - for (i = 0; i < rclPoly.GetCtVectors(); i++) { + for (unsigned long i = 0; i < rclPoly.GetCtVectors(); i++) { if (Contains(rclPoly[i])) { return true; /***** RETURN INTERSECTION *********/ } @@ -142,7 +132,7 @@ bool BoundBox2d::Intersect(const Polygon2d& rclPoly) const if (rclPoly.GetCtVectors() < 3) { return false; } - for (i = 0; i < rclPoly.GetCtVectors(); i++) { + for (unsigned long i = 0; i < rclPoly.GetCtVectors(); i++) { if (i == rclPoly.GetCtVectors() - 1) { clLine.clV1 = rclPoly[i]; clLine.clV2 = rclPoly[0]; @@ -174,7 +164,10 @@ BoundBox2d Line2d::CalcBoundBox() const bool Line2d::Intersect(const Line2d& rclLine, Vector2d& rclV) const { - double m1 = 0.0, m2 = 0.0, b1 = 0.0, b2 = 0.0; + double m1 = 0.0; + double m2 = 0.0; + double b1 = 0.0; + double b2 = 0.0; // calc coefficients if (fabs(clV2.x - clV1.x) > 1e-10) { @@ -231,10 +224,7 @@ bool Line2d::Intersect(const Vector2d& rclV, double eps) const // point is on line but it is also between V1 and V2? double dot = dxc * dxl + dyc * dyl; double len = dxl * dxl + dyl * dyl; - if (dot < -eps || dot > len + eps) { - return false; - } - return true; + return (dot >= -eps && dot <= len + eps); } Vector2d Line2d::FromPos(double fDistance) const @@ -269,19 +259,18 @@ BoundBox2d Polygon2d::CalcBoundBox() const return clBB; } -static short _CalcTorsion(double* pfLine, double fX, double fY) +static short CalcTorsion(const std::array& pfLine, double fX, double fY) { - int sQuad[2], - i = 0; // Changing this from short to int allows the compiler to inline this function + std::array sQuad {}; double fResX = 0.0; // Classification of both polygon points into quadrants - for (i = 0; i < 2; i++) { - if (pfLine[i * 2] <= fX) { - sQuad[i] = (pfLine[i * 2 + 1] > fY) ? 0 : 3; + for (std::size_t i = 0; i < 2; i++) { + if (pfLine.at(i * 2) <= fX) { + sQuad[i] = (pfLine.at(i * 2 + 1) > fY) ? 0 : 3; } else { - sQuad[i] = (pfLine[i * 2 + 1] > fY) ? 1 : 2; + sQuad[i] = (pfLine.at(i * 2 + 1) > fY) ? 1 : 2; } } @@ -314,7 +303,7 @@ bool Polygon2d::Contains(const Vector2d& rclV) const // Using the number of turns method, determines // whether a point is contained within a polygon. // The sum of all turns indicates whether yes or no. - double pfTmp[4]; + std::array pfTmp {}; unsigned long i = 0; short sTorsion = 0; @@ -342,7 +331,7 @@ bool Polygon2d::Contains(const Vector2d& rclV) const } // Carry out a cut test and calculate the turn counter - sTorsion += _CalcTorsion(pfTmp, rclV.x, rclV.y); + sTorsion += CalcTorsion(pfTmp, rclV.x, rclV.y); } // Evaluate turn counter @@ -390,7 +379,7 @@ void Polygon2d::Intersect(const Polygon2d& rclPolygon, } } - if (afIntersections.size() > 0) // intersections founded + if (!afIntersections.empty()) // intersections founded { for (double it : afIntersections) { // intersection point diff --git a/src/Base/Tools2D.h b/src/Base/Tools2D.h index c4538d1aa8..61b4abbf22 100644 --- a/src/Base/Tools2D.h +++ b/src/Base/Tools2D.h @@ -93,7 +93,7 @@ public: inline double Distance(const Vector2d& v) const; inline bool IsEqual(const Vector2d& v, double tolerance = 0.0) const; - double GetAngle(const Vector2d& v) const; + double GetAngle(const Vector2d& vec) const; void ProjectToLine(const Vector2d& point, const Vector2d& line); }; @@ -112,13 +112,13 @@ public: inline BoundBox2d(BoundBox2d&&) = default; inline BoundBox2d(double fX1, double fY1, double fX2, double fY2); ~BoundBox2d() = default; - inline bool IsValid(); - inline bool IsEqual(const BoundBox2d&, double tolerance) const; + inline bool IsValid() const; + inline bool IsEqual(const BoundBox2d& bbox, double tolerance) const; // operators inline BoundBox2d& operator=(const BoundBox2d&) = default; inline BoundBox2d& operator=(BoundBox2d&&) = default; - inline bool operator==(const BoundBox2d& rclBB) const; + inline bool operator==(const BoundBox2d& bbox) const; // methods inline double Width() const; @@ -182,7 +182,7 @@ public: ~Polygon2d() = default; inline Polygon2d& operator=(const Polygon2d& rclP); - inline Polygon2d& operator=(Polygon2d&& rclP); + inline Polygon2d& operator=(Polygon2d&& rclP) noexcept; // admin-interface inline size_t GetCtVectors() const; @@ -198,7 +198,7 @@ public: BoundBox2d CalcBoundBox() const; bool Contains(const Vector2d& rclV) const; void Intersect(const Polygon2d& rclPolygon, std::list& rclResultPolygonList) const; - bool Intersect(const Polygon2d& rclPolygon) const; + bool Intersect(const Polygon2d& other) const; bool Intersect(const Vector2d& rclV, double eps) const; private: @@ -382,7 +382,7 @@ inline bool Vector2d::IsEqual(const Vector2d& v, double tolerance) const inline Polygon2d& Polygon2d::operator=(const Polygon2d& rclP) = default; -inline Polygon2d& Polygon2d::operator=(Polygon2d&& rclP) = default; +inline Polygon2d& Polygon2d::operator=(Polygon2d&& rclP) noexcept = default; inline void Polygon2d::DeleteAll() { @@ -466,21 +466,23 @@ inline BoundBox2d::BoundBox2d(double fX1, double fY1, double fX2, double fY2) , MaxY(std::max(fY1, fY2)) {} -inline bool BoundBox2d::IsValid() +inline bool BoundBox2d::IsValid() const { return (MaxX >= MinX) && (MaxY >= MinY); } -inline bool BoundBox2d::IsEqual(const BoundBox2d& b, double tolerance) const +inline bool BoundBox2d::IsEqual(const BoundBox2d& bbox, double tolerance) const { - return Vector2d(MinX, MinY).IsEqual(Vector2d(b.MinX, b.MinY), tolerance) - && Vector2d(MaxX, MaxY).IsEqual(Vector2d(b.MaxX, b.MaxY), tolerance); + return Vector2d(MinX, MinY).IsEqual(Vector2d(bbox.MinX, bbox.MinY), tolerance) + && Vector2d(MaxX, MaxY).IsEqual(Vector2d(bbox.MaxX, bbox.MaxY), tolerance); } -inline bool BoundBox2d::operator==(const BoundBox2d& rclBB) const +inline bool BoundBox2d::operator==(const BoundBox2d& bbox) const { - return (MinX == rclBB.MinX) && (MinY == rclBB.MinY) && (MaxX == rclBB.MaxX) - && (MaxY == rclBB.MaxY); + // clang-format off + return (MinX == bbox.MinX) && (MinY == bbox.MinY) + && (MaxX == bbox.MaxX) && (MaxY == bbox.MaxY); + // clang-format on } inline double BoundBox2d::Width() const diff --git a/src/Base/Tools3D.cpp b/src/Base/Tools3D.cpp index eefc88f7be..3cf103e96a 100644 --- a/src/Base/Tools3D.cpp +++ b/src/Base/Tools3D.cpp @@ -160,9 +160,9 @@ size_t Polygon3::GetSize() const } template -void Polygon3::Add(const Vector3& p) +void Polygon3::Add(const Vector3& pnt) { - points.push_back(p); + points.push_back(pnt); } template diff --git a/src/Base/Tools3D.h b/src/Base/Tools3D.h index 13b8e1839b..f8dfbe39c4 100644 --- a/src/Base/Tools3D.h +++ b/src/Base/Tools3D.h @@ -60,12 +60,12 @@ public: Line3() = default; ~Line3() = default; Line3(const Line3& line) = default; - Line3(Line3&& line) = default; + Line3(Line3&& line) noexcept = default; Line3(const Vector3& p1, const Vector3& p2); // operators Line3& operator=(const Line3& line) = default; - Line3& operator=(Line3&& line) = default; + Line3& operator=(Line3&& line) noexcept = default; bool operator==(const Line3& line) const; // methods @@ -84,19 +84,19 @@ public: /*! * \brief Contains * Checks if the point \a p is part of the line segment. - * \param p + * \param pt * \return */ - bool Contains(const Vector3& p) const; + bool Contains(const Vector3& pt) const; /*! * \brief Contains * Checks if the distance of point \a p to the line segment is * less than \a eps - * \param p + * \param pt * \param eps * \return */ - bool Contains(const Vector3& p, float_type eps) const; + bool Contains(const Vector3& pt, float_type eps) const; Vector3 FromPos(float_type distance) const; }; @@ -112,13 +112,13 @@ public: Polygon3() = default; ~Polygon3() = default; Polygon3(const Polygon3& poly) = default; - Polygon3(Polygon3&& poly) = default; + Polygon3(Polygon3&& poly) noexcept = default; Polygon3& operator=(const Polygon3& poly) = default; - Polygon3& operator=(Polygon3&& poly) = default; + Polygon3& operator=(Polygon3&& poly) noexcept = default; size_t GetSize() const; - void Add(const Vector3& p); + void Add(const Vector3& pnt); const Vector3& operator[](size_t pos) const; const Vector3& At(size_t pos) const; Vector3& operator[](size_t pos); diff --git a/src/Base/Translate.cpp b/src/Base/Translate.cpp index f900c0685b..de66aea3a2 100644 --- a/src/Base/Translate.cpp +++ b/src/Base/Translate.cpp @@ -85,12 +85,12 @@ Py::Object Translate::translate(const Py::Tuple& args) char* context = nullptr; char* source = nullptr; char* disambiguation = nullptr; - int n = -1; - if (!PyArg_ParseTuple(args.ptr(), "ss|zi", &context, &source, &disambiguation, &n)) { + int num = -1; + if (!PyArg_ParseTuple(args.ptr(), "ss|zi", &context, &source, &disambiguation, &num)) { throw Py::Exception(); } - QString str = QCoreApplication::translate(context, source, disambiguation, n); + QString str = QCoreApplication::translate(context, source, disambiguation, num); return Py::asObject(PyUnicode_FromString(str.toUtf8())); } diff --git a/src/Base/Type.cpp b/src/Base/Type.cpp index b5afda9055..f137ba55bf 100644 --- a/src/Base/Type.cpp +++ b/src/Base/Type.cpp @@ -74,12 +74,12 @@ void* Type::createInstanceByName(const char* TypeName, bool bLoadModule) } // now the type should be in the type map - Type t = fromName(TypeName); - if (t == badType()) { + Type type = fromName(TypeName); + if (type == badType()) { return nullptr; } - return t.createInstance(); + return type.createInstance(); } void Type::importModule(const char* TypeName) @@ -119,7 +119,7 @@ Type Type::badType() } -const Type Type::createType(const Type parent, const char* name, instantiationMethod method) +Type Type::createType(const Type& parent, const char* name, instantiationMethod method) { Type newType; newType.index = static_cast(Type::typedata.size()); @@ -135,7 +135,7 @@ const Type Type::createType(const Type parent, const char* name, instantiationMe void Type::init() { - assert(Type::typedata.size() == 0); + assert(Type::typedata.empty()); Type::typedata.push_back(new TypeData("BadType")); @@ -160,9 +160,8 @@ Type Type::fromName(const char* name) if (pos != typemap.end()) { return typedata[pos->second]->type; } - else { - return Type::badType(); - } + + return Type::badType(); } Type Type::fromKey(unsigned int key) @@ -170,9 +169,8 @@ Type Type::fromKey(unsigned int key) if (key < typedata.size()) { return typedata[key]->type; } - else { - return Type::badType(); - } + + return Type::badType(); } const char* Type::getName() const @@ -180,12 +178,12 @@ const char* Type::getName() const return typedata[index]->name.c_str(); } -const Type Type::getParent() const +Type Type::getParent() const { return typedata[index]->parent; } -bool Type::isDerivedFrom(const Type type) const +bool Type::isDerivedFrom(const Type& type) const { Type temp(*this); @@ -199,7 +197,7 @@ bool Type::isDerivedFrom(const Type type) const return false; } -int Type::getAllDerivedFrom(const Type type, std::vector& List) +int Type::getAllDerivedFrom(const Type& type, std::vector& List) { int cnt = 0; @@ -217,7 +215,7 @@ int Type::getNumTypes() return static_cast(typedata.size()); } -Type Type::getTypeIfDerivedFrom(const char* name, const Type parent, bool bLoadModule) +Type Type::getTypeIfDerivedFrom(const char* name, const Type& parent, bool bLoadModule) { if (bLoadModule) { importModule(name); @@ -228,7 +226,6 @@ Type Type::getTypeIfDerivedFrom(const char* name, const Type parent, bool bLoadM if (type.isDerivedFrom(parent)) { return type; } - else { - return Type::badType(); - } + + return Type::badType(); } diff --git a/src/Base/Type.h b/src/Base/Type.h index e2e93e3057..cf138ade2f 100644 --- a/src/Base/Type.h +++ b/src/Base/Type.h @@ -98,30 +98,31 @@ public: static Type fromName(const char* name); static Type fromKey(unsigned int key); const char* getName() const; - const Type getParent() const; - bool isDerivedFrom(const Type type) const; + Type getParent() const; + bool isDerivedFrom(const Type& type) const; - static int getAllDerivedFrom(const Type type, std::vector& List); + static int getAllDerivedFrom(const Type& type, std::vector& List); /// Returns the given named type if is derived from parent type, otherwise return bad type - static Type getTypeIfDerivedFrom(const char* name, const Type parent, bool bLoadModule = false); + static Type + getTypeIfDerivedFrom(const char* name, const Type& parent, bool bLoadModule = false); static int getNumTypes(); - static const Type - createType(const Type parent, const char* name, instantiationMethod method = nullptr); + static Type + createType(const Type& parent, const char* name, instantiationMethod method = nullptr); unsigned int getKey() const; bool isBad() const; Type& operator=(const Type& type) = default; Type& operator=(Type&& type) = default; - bool operator==(const Type type) const; - bool operator!=(const Type type) const; + bool operator==(const Type& type) const; + bool operator!=(const Type& type) const; - bool operator<(const Type type) const; - bool operator<=(const Type type) const; - bool operator>=(const Type type) const; - bool operator>(const Type type) const; + bool operator<(const Type& type) const; + bool operator<=(const Type& type) const; + bool operator>=(const Type& type) const; + bool operator>(const Type& type) const; static Type badType(); static void init(); @@ -145,32 +146,32 @@ inline unsigned int Type::getKey() const return this->index; } -inline bool Type::operator!=(const Type type) const +inline bool Type::operator!=(const Type& type) const { return (this->getKey() != type.getKey()); } -inline bool Type::operator==(const Type type) const +inline bool Type::operator==(const Type& type) const { return (this->getKey() == type.getKey()); } -inline bool Type::operator<(const Type type) const +inline bool Type::operator<(const Type& type) const { return (this->getKey() < type.getKey()); } -inline bool Type::operator<=(const Type type) const +inline bool Type::operator<=(const Type& type) const { return (this->getKey() <= type.getKey()); } -inline bool Type::operator>=(const Type type) const +inline bool Type::operator>=(const Type& type) const { return (this->getKey() >= type.getKey()); } -inline bool Type::operator>(const Type type) const +inline bool Type::operator>(const Type& type) const { return (this->getKey() > type.getKey()); } diff --git a/src/Base/TypePyImp.cpp b/src/Base/TypePyImp.cpp index c957a5e281..d8e9016407 100644 --- a/src/Base/TypePyImp.cpp +++ b/src/Base/TypePyImp.cpp @@ -97,8 +97,8 @@ PyObject* TypePy::isBad(PyObject* args) return nullptr; } - bool v = getBaseTypePtr()->isBad(); - return PyBool_FromLong(v ? 1 : 0); + bool val = getBaseTypePtr()->isBad(); + return PyBool_FromLong(val ? 1 : 0); } PyObject* TypePy::isDerivedFrom(PyObject* args) @@ -113,9 +113,9 @@ PyObject* TypePy::isDerivedFrom(PyObject* args) } PyErr_Clear(); - PyObject* t {}; - if (PyArg_ParseTuple(args, "O!", &TypePy::Type, &t)) { - type = *static_cast(t)->getBaseTypePtr(); + PyObject* py {}; + if (PyArg_ParseTuple(args, "O!", &TypePy::Type, &py)) { + type = *static_cast(py)->getBaseTypePtr(); break; } @@ -123,8 +123,8 @@ PyObject* TypePy::isDerivedFrom(PyObject* args) return nullptr; } while (false); - bool v = (type != Base::Type::badType() && getBaseTypePtr()->isDerivedFrom(type)); - return PyBool_FromLong(v ? 1 : 0); + bool val = (type != Base::Type::badType() && getBaseTypePtr()->isDerivedFrom(type)); + return PyBool_FromLong(val ? 1 : 0); } PyObject* TypePy::getAllDerivedFrom(PyObject* args) @@ -139,9 +139,9 @@ PyObject* TypePy::getAllDerivedFrom(PyObject* args) } PyErr_Clear(); - PyObject* t {}; - if (PyArg_ParseTuple(args, "O!", &TypePy::Type, &t)) { - type = *static_cast(t)->getBaseTypePtr(); + PyObject* py {}; + if (PyArg_ParseTuple(args, "O!", &TypePy::Type, &py)) { + type = *static_cast(py)->getBaseTypePtr(); break; } @@ -176,7 +176,7 @@ PyObject* TypePy::getAllDerived(PyObject* args) namespace { -static void deallocPyObject(PyObject* py) +void deallocPyObject(PyObject* py) { Base::PyObjectBase* pybase = static_cast(py); Base::BaseClass* base = static_cast(pybase->getTwinPointer()); @@ -188,7 +188,7 @@ static void deallocPyObject(PyObject* py) Base::PyObjectBase::PyDestructor(py); } -static PyObject* createPyObject(Base::BaseClass* base) +PyObject* createPyObject(Base::BaseClass* base) { PyObject* py = base->getPyObject(); diff --git a/src/Base/Unit.cpp b/src/Base/Unit.cpp index dcebc1d3aa..2092392b66 100644 --- a/src/Base/Unit.cpp +++ b/src/Base/Unit.cpp @@ -62,8 +62,9 @@ static inline void checkRange(const char * op, int length, int mass, int time, i ( thermodynamicTemperature >= (1 << (UnitSignatureThermodynamicTemperatureBits - 1)) ) || ( amountOfSubstance >= (1 << (UnitSignatureAmountOfSubstanceBits - 1)) ) || ( luminousIntensity >= (1 << (UnitSignatureLuminousIntensityBits - 1)) ) || - ( angle >= (1 << (UnitSignatureAngleBits - 1)) ) ) + ( angle >= (1 << (UnitSignatureAngleBits - 1)) ) ) { throw Base::OverflowError((std::string("Unit overflow in ") + std::string(op)).c_str()); + } if ( ( length < -(1 << (UnitSignatureLengthBits - 1)) ) || ( mass < -(1 << (UnitSignatureMassBits - 1)) ) || ( time < -(1 << (UnitSignatureTimeBits - 1)) ) || @@ -71,8 +72,9 @@ static inline void checkRange(const char * op, int length, int mass, int time, i ( thermodynamicTemperature < -(1 << (UnitSignatureThermodynamicTemperatureBits - 1)) ) || ( amountOfSubstance < -(1 << (UnitSignatureAmountOfSubstanceBits - 1)) ) || ( luminousIntensity < -(1 << (UnitSignatureLuminousIntensityBits - 1)) ) || - ( angle < -(1 << (UnitSignatureAngleBits - 1)) ) ) + ( angle < -(1 << (UnitSignatureAngleBits - 1)) ) ) { throw Base::UnderflowError((std::string("Unit underflow in ") + std::string(op)).c_str()); + } } Unit::Unit(int8_t Length, //NOLINT @@ -117,12 +119,7 @@ Unit::Unit() //NOLINT Sig.Angle = 0; } -Unit::Unit(const Unit& that) -{ - this->Sig = that.Sig; -} - -Unit::Unit(const QString& expr) +Unit::Unit(const QString& expr) // NOLINT { try { *this = Quantity::parse(expr).getUnit(); @@ -240,26 +237,13 @@ Unit Unit::operator /(const Unit &right) const return result; } -Unit& Unit::operator = (const Unit &New) -{ - Sig.Length = New.Sig.Length; - Sig.Mass = New.Sig.Mass; - Sig.Time = New.Sig.Time; - Sig.ElectricCurrent = New.Sig.ElectricCurrent; - Sig.ThermodynamicTemperature = New.Sig.ThermodynamicTemperature; - Sig.AmountOfSubstance = New.Sig.AmountOfSubstance; - Sig.LuminousIntensity = New.Sig.LuminousIntensity; - Sig.Angle = New.Sig.Angle; - - return *this; -} - QString Unit::getString() const { std::stringstream ret; - if (isEmpty()) + if (isEmpty()) { return {}; + } if (Sig.Length > 0 || Sig.Mass > 0 || @@ -274,70 +258,86 @@ QString Unit::getString() const if (Sig.Length > 0) { mult = true; ret << "mm"; - if (Sig.Length > 1) + if (Sig.Length > 1) { ret << "^" << Sig.Length; + } } if (Sig.Mass > 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; ret << "kg"; - if (Sig.Mass > 1) + if (Sig.Mass > 1) { ret << "^" << Sig.Mass; + } } if (Sig.Time > 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; ret << "s"; - if (Sig.Time > 1) + if (Sig.Time > 1) { ret << "^" << Sig.Time; + } } if (Sig.ElectricCurrent > 0) { - if (mult) ret<<'*'; - mult = true; + if (mult) { + ret<<'*'; + } + mult = true; ret << "A"; - if (Sig.ElectricCurrent > 1) + if (Sig.ElectricCurrent > 1) { ret << "^" << Sig.ElectricCurrent; + } } if (Sig.ThermodynamicTemperature > 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; ret << "K"; - if (Sig.ThermodynamicTemperature > 1) + if (Sig.ThermodynamicTemperature > 1) { ret << "^" << Sig.ThermodynamicTemperature; + } } if (Sig.AmountOfSubstance > 0){ - if (mult) + if (mult) { ret<<'*'; + } mult = true; ret << "mol"; - if (Sig.AmountOfSubstance > 1) + if (Sig.AmountOfSubstance > 1) { ret << "^" << Sig.AmountOfSubstance; + } } if (Sig.LuminousIntensity > 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; ret << "cd"; - if (Sig.LuminousIntensity > 1) + if (Sig.LuminousIntensity > 1) { ret << "^" << Sig.LuminousIntensity; + } } if (Sig.Angle > 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; //NOLINT ret << "deg"; - if (Sig.Angle > 1) + if (Sig.Angle > 1) { ret << "^" << Sig.Angle; + } } } else { @@ -364,82 +364,99 @@ QString Unit::getString() const nnom += Sig.LuminousIntensity<0?1:0; nnom += Sig.Angle<0?1:0; - if (nnom > 1) + if (nnom > 1) { ret << '('; + } bool mult=false; if (Sig.Length < 0) { ret << "mm"; mult = true; - if (Sig.Length < -1) + if (Sig.Length < -1) { ret << "^" << abs(Sig.Length); + } } if (Sig.Mass < 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; ret << "kg"; - if (Sig.Mass < -1) + if (Sig.Mass < -1) { ret << "^" << abs(Sig.Mass); + } } if (Sig.Time < 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; ret << "s"; - if (Sig.Time < -1) + if (Sig.Time < -1) { ret << "^" << abs(Sig.Time); + } } if (Sig.ElectricCurrent < 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; ret << "A"; - if (Sig.ElectricCurrent < -1) + if (Sig.ElectricCurrent < -1) { ret << "^" << abs(Sig.ElectricCurrent); + } } if (Sig.ThermodynamicTemperature < 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; ret << "K"; - if (Sig.ThermodynamicTemperature < -1) + if (Sig.ThermodynamicTemperature < -1) { ret << "^" << abs(Sig.ThermodynamicTemperature); + } } if (Sig.AmountOfSubstance < 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; ret << "mol"; - if (Sig.AmountOfSubstance < -1) + if (Sig.AmountOfSubstance < -1) { ret << "^" << abs(Sig.AmountOfSubstance); + } } if (Sig.LuminousIntensity < 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; ret << "cd"; - if (Sig.LuminousIntensity < -1) + if (Sig.LuminousIntensity < -1) { ret << "^" << abs(Sig.LuminousIntensity); + } } if (Sig.Angle < 0) { - if (mult) + if (mult) { ret<<'*'; + } mult = true; //NOLINT ret << "deg"; - if (Sig.Angle < -1) + if (Sig.Angle < -1) { ret << "^" << abs(Sig.Angle); + } } - if (nnom > 1) + if (nnom > 1) { ret << ')'; + } } return QString::fromUtf8(ret.str().c_str()); @@ -447,110 +464,162 @@ QString Unit::getString() const QString Unit::getTypeString() const { - if (*this == Unit::Acceleration) + if (*this == Unit::Acceleration) { return QString::fromLatin1("Acceleration"); - if (*this == Unit::AmountOfSubstance) + } + if (*this == Unit::AmountOfSubstance) { return QString::fromLatin1("AmountOfSubstance"); - if (*this == Unit::Angle) + } + if (*this == Unit::Angle) { return QString::fromLatin1("Angle"); - if (*this == Unit::AngleOfFriction) + } + if (*this == Unit::AngleOfFriction) { return QString::fromLatin1("AngleOfFriction"); - if (*this == Unit::Area) + } + if (*this == Unit::Area) { return QString::fromLatin1("Area"); - if (*this == Unit::CurrentDensity) + } + if (*this == Unit::CurrentDensity) { return QString::fromLatin1("CurrentDensity"); - if (*this == Unit::Density) + } + if (*this == Unit::Density) { return QString::fromLatin1("Density"); - if (*this == Unit::DissipationRate) + } + if (*this == Unit::DissipationRate) { return QString::fromLatin1("DissipationRate"); - if (*this == Unit::DynamicViscosity) + } + if (*this == Unit::DynamicViscosity) { return QString::fromLatin1("DynamicViscosity"); - if (*this == Unit::ElectricalCapacitance) + } + if (*this == Unit::ElectricalCapacitance) { return QString::fromLatin1("ElectricalCapacitance"); - if (*this == Unit::ElectricalConductance) + } + if (*this == Unit::ElectricalConductance) { return QString::fromLatin1("ElectricalConductance"); - if (*this == Unit::ElectricalConductivity) + } + if (*this == Unit::ElectricalConductivity) { return QString::fromLatin1("ElectricalConductivity"); - if (*this == Unit::ElectricalInductance) + } + if (*this == Unit::ElectricalInductance) { return QString::fromLatin1("ElectricalInductance"); - if (*this == Unit::ElectricalResistance) + } + if (*this == Unit::ElectricalResistance) { return QString::fromLatin1("ElectricalResistance"); - if (*this == Unit::ElectricCharge) + } + if (*this == Unit::ElectricCharge) { return QString::fromLatin1("ElectricCharge"); - if (*this == Unit::ElectricCurrent) + } + if (*this == Unit::ElectricCurrent) { return QString::fromLatin1("ElectricCurrent"); - if (*this == Unit::ElectricPotential) + } + if (*this == Unit::ElectricPotential) { return QString::fromLatin1("ElectricPotential"); - if (*this == Unit::Frequency) + } + if (*this == Unit::Frequency) { return QString::fromLatin1("Frequency"); - if (*this == Unit::Force) + } + if (*this == Unit::Force) { return QString::fromLatin1("Force"); - if (*this == Unit::HeatFlux) + } + if (*this == Unit::HeatFlux) { return QString::fromLatin1("HeatFlux"); - if (*this == Unit::InverseArea) + } + if (*this == Unit::InverseArea) { return QString::fromLatin1("InverseArea"); - if (*this == Unit::InverseLength) + } + if (*this == Unit::InverseLength) { return QString::fromLatin1("InverseLength"); - if (*this == Unit::InverseVolume) + } + if (*this == Unit::InverseVolume) { return QString::fromLatin1("InverseVolume"); - if (*this == Unit::KinematicViscosity) + } + if (*this == Unit::KinematicViscosity) { return QString::fromLatin1("KinematicViscosity"); - if (*this == Unit::Length) + } + if (*this == Unit::Length) { return QString::fromLatin1("Length"); - if (*this == Unit::LuminousIntensity) + } + if (*this == Unit::LuminousIntensity) { return QString::fromLatin1("LuminousIntensity"); - if (*this == Unit::MagneticFieldStrength) + } + if (*this == Unit::MagneticFieldStrength) { return QString::fromLatin1("MagneticFieldStrength"); - if (*this == Unit::MagneticFlux) + } + if (*this == Unit::MagneticFlux) { return QString::fromLatin1("MagneticFlux"); - if (*this == Unit::MagneticFluxDensity) + } + if (*this == Unit::MagneticFluxDensity) { return QString::fromLatin1("MagneticFluxDensity"); - if (*this == Unit::Magnetization) + } + if (*this == Unit::Magnetization) { return QString::fromLatin1("Magnetization"); - if (*this == Unit::Mass) + } + if (*this == Unit::Mass) { return QString::fromLatin1("Mass"); - if (*this == Unit::Pressure) + } + if (*this == Unit::Pressure) { return QString::fromLatin1("Pressure"); - if (*this == Unit::Power) + } + if (*this == Unit::Power) { return QString::fromLatin1("Power"); - if (*this == Unit::ShearModulus) + } + if (*this == Unit::ShearModulus) { return QString::fromLatin1("ShearModulus"); - if (*this == Unit::SpecificEnergy) + } + if (*this == Unit::SpecificEnergy) { return QString::fromLatin1("SpecificEnergy"); - if (*this == Unit::SpecificHeat) + } + if (*this == Unit::SpecificHeat) { return QString::fromLatin1("SpecificHeat"); - if (*this == Unit::Stiffness) + } + if (*this == Unit::Stiffness) { return QString::fromLatin1("Stiffness"); - if (*this == Unit::Stress) + } + if (*this == Unit::Stress) { return QString::fromLatin1("Stress"); - if (*this == Unit::Temperature) + } + if (*this == Unit::Temperature) { return QString::fromLatin1("Temperature"); - if (*this == Unit::ThermalConductivity) + } + if (*this == Unit::ThermalConductivity) { return QString::fromLatin1("ThermalConductivity"); - if (*this == Unit::ThermalExpansionCoefficient) + } + if (*this == Unit::ThermalExpansionCoefficient) { return QString::fromLatin1("ThermalExpansionCoefficient"); - if (*this == Unit::ThermalTransferCoefficient) + } + if (*this == Unit::ThermalTransferCoefficient) { return QString::fromLatin1("ThermalTransferCoefficient"); - if (*this == Unit::TimeSpan) + } + if (*this == Unit::TimeSpan) { return QString::fromLatin1("TimeSpan"); - if (*this == Unit::UltimateTensileStrength) + } + if (*this == Unit::UltimateTensileStrength) { return QString::fromLatin1("UltimateTensileStrength"); - if (*this == Unit::VacuumPermittivity) + } + if (*this == Unit::VacuumPermittivity) { return QString::fromLatin1("VacuumPermittivity"); - if (*this == Unit::Velocity) + } + if (*this == Unit::Velocity) { return QString::fromLatin1("Velocity"); - if (*this == Unit::Volume) + } + if (*this == Unit::Volume) { return QString::fromLatin1("Volume"); - if (*this == Unit::VolumeFlowRate) + } + if (*this == Unit::VolumeFlowRate) { return QString::fromLatin1("VolumeFlowRate"); - if (*this == Unit::VolumetricThermalExpansionCoefficient) + } + if (*this == Unit::VolumetricThermalExpansionCoefficient) { return QString::fromLatin1("VolumetricThermalExpansionCoefficient"); - if (*this == Unit::Work) + } + if (*this == Unit::Work) { return QString::fromLatin1("Work"); - if (*this == Unit::YieldStrength) + } + if (*this == Unit::YieldStrength) { return QString::fromLatin1("YieldStrength"); - if (*this == Unit::YoungsModulus) + } + if (*this == Unit::YoungsModulus) { return QString::fromLatin1("YoungsModulus"); + } return {}; } diff --git a/src/Base/Unit.h b/src/Base/Unit.h index fc0b0db761..1e55763a04 100644 --- a/src/Base/Unit.h +++ b/src/Base/Unit.h @@ -70,7 +70,8 @@ public: int8_t LuminousIntensity = 0, int8_t Angle = 0); Unit(); - Unit(const Unit&); + Unit(const Unit&) = default; + Unit(Unit&&) = default; explicit Unit(const QString& expr); /// Destruction ~Unit() = default; @@ -87,7 +88,8 @@ public: { return !(*this == that); } - Unit& operator=(const Unit&); + Unit& operator=(const Unit&) = default; + Unit& operator=(Unit&&) = default; Unit pow(double exp) const; //@} /// get the unit signature @@ -171,7 +173,7 @@ public: static Unit InverseVolume; //@} -protected: +private: UnitSignature Sig; }; diff --git a/src/Base/UnitPyImp.cpp b/src/Base/UnitPyImp.cpp index a658aa83f6..e8db65865a 100644 --- a/src/Base/UnitPyImp.cpp +++ b/src/Base/UnitPyImp.cpp @@ -54,7 +54,7 @@ std::string UnitPy::representation() const return ret.str(); } -PyObject* UnitPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper +PyObject* UnitPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { // create a new instance of UnitPy and the Twin object return new UnitPy(new Unit); diff --git a/src/Base/UnitsApi.cpp b/src/Base/UnitsApi.cpp index ed3c20acef..eb25c42e4d 100644 --- a/src/Base/UnitsApi.cpp +++ b/src/Base/UnitsApi.cpp @@ -182,10 +182,10 @@ QString UnitsApi::schemaTranslate(const Base::Quantity& quant, double& factor, Q return UserPrefSystem->schemaTranslate(quant, factor, unitString); } -double UnitsApi::toDouble(PyObject* ArgObj, const Base::Unit& u) +double UnitsApi::toDouble(PyObject* args, const Base::Unit& u) { - if (PyUnicode_Check(ArgObj)) { - QString str = QString::fromUtf8(PyUnicode_AsUTF8(ArgObj)); + if (PyUnicode_Check(args)) { + QString str = QString::fromUtf8(PyUnicode_AsUTF8(args)); // Parse the string Quantity q = Quantity::parse(str); if (q.getUnit() == u) { @@ -193,31 +193,30 @@ double UnitsApi::toDouble(PyObject* ArgObj, const Base::Unit& u) } throw Base::UnitsMismatchError("Wrong unit type!"); } - else if (PyFloat_Check(ArgObj)) { - return PyFloat_AsDouble(ArgObj); + if (PyFloat_Check(args)) { + return PyFloat_AsDouble(args); } - else if (PyLong_Check(ArgObj)) { - return static_cast(PyLong_AsLong(ArgObj)); - } - else { - throw Base::UnitsMismatchError("Wrong parameter type!"); + if (PyLong_Check(args)) { + return static_cast(PyLong_AsLong(args)); } + + throw Base::UnitsMismatchError("Wrong parameter type!"); } -Quantity UnitsApi::toQuantity(PyObject* ArgObj, const Base::Unit& u) +Quantity UnitsApi::toQuantity(PyObject* args, const Base::Unit& u) { double d {}; - if (PyUnicode_Check(ArgObj)) { - QString str = QString::fromUtf8(PyUnicode_AsUTF8(ArgObj)); + if (PyUnicode_Check(args)) { + QString str = QString::fromUtf8(PyUnicode_AsUTF8(args)); // Parse the string Quantity q = Quantity::parse(str); d = q.getValue(); } - else if (PyFloat_Check(ArgObj)) { - d = PyFloat_AsDouble(ArgObj); + else if (PyFloat_Check(args)) { + d = PyFloat_AsDouble(args); } - else if (PyLong_Check(ArgObj)) { - d = static_cast(PyLong_AsLong(ArgObj)); + else if (PyLong_Check(args)) { + d = static_cast(PyLong_AsLong(args)); } else { throw Base::UnitsMismatchError("Wrong parameter type!"); diff --git a/src/Base/UnitsApi.h b/src/Base/UnitsApi.h index 1837bae019..66a0e18487 100644 --- a/src/Base/UnitsApi.h +++ b/src/Base/UnitsApi.h @@ -87,7 +87,7 @@ public: * needed represented in scientific notation. The string doesn't include the unit of the * quantity. */ - static QString toNumber(double d, + static QString toNumber(double value, const QuantityFormat& f = QuantityFormat(QuantityFormat::Default)); /// generate a value for a quantity with default user preferred system diff --git a/src/Base/UnitsApiPy.cpp b/src/Base/UnitsApiPy.cpp index 99c41c426f..ba14c0726f 100644 --- a/src/Base/UnitsApiPy.cpp +++ b/src/Base/UnitsApiPy.cpp @@ -158,17 +158,17 @@ PyObject* UnitsApi::sSetSchema(PyObject* /*self*/, PyObject* args) PyObject* UnitsApi::sSchemaTranslate(PyObject* /*self*/, PyObject* args) { - PyObject* q {}; + PyObject* py {}; int index {}; - if (!PyArg_ParseTuple(args, "O!i", &(QuantityPy::Type), &q, &index)) { + if (!PyArg_ParseTuple(args, "O!i", &(QuantityPy::Type), &py, &index)) { return nullptr; } Quantity quant; - quant = *static_cast(q)->getQuantityPtr(); + quant = *static_cast(py)->getQuantityPtr(); std::unique_ptr schema(createSchema(static_cast(index))); - if (!schema.get()) { + if (!schema) { PyErr_SetString(PyExc_ValueError, "invalid schema value"); return nullptr; } @@ -192,9 +192,9 @@ PyObject* UnitsApi::sToNumber(PyObject* /*self*/, PyObject* args) int decimals {}; do { - PyObject* q {}; - if (PyArg_ParseTuple(args, "O!|si", &(QuantityPy::Type), &q, &format, &decimals)) { - value = static_cast(q)->getQuantityPtr()->getValue(); + PyObject* py {}; + if (PyArg_ParseTuple(args, "O!|si", &(QuantityPy::Type), &py, &format, &decimals)) { + value = static_cast(py)->getQuantityPtr()->getValue(); break; } diff --git a/src/Base/UnitsSchema.h b/src/Base/UnitsSchema.h index 7eb3c86ca4..2a0e199e7c 100644 --- a/src/Base/UnitsSchema.h +++ b/src/Base/UnitsSchema.h @@ -56,6 +56,11 @@ enum class UnitSystem class UnitsSchema { public: + UnitsSchema() = default; + UnitsSchema(const UnitsSchema&) = default; + UnitsSchema(UnitsSchema&&) = default; + UnitsSchema& operator=(const UnitsSchema&) = default; + UnitsSchema& operator=(UnitsSchema&&) = default; virtual ~UnitsSchema() = default; /** Gets called if this schema gets activated. * Here it's theoretically possible that you can change the static factors diff --git a/src/Base/UnitsSchemaImperial1.cpp b/src/Base/UnitsSchemaImperial1.cpp index 99d4c10ed2..b838987df2 100644 --- a/src/Base/UnitsSchemaImperial1.cpp +++ b/src/Base/UnitsSchemaImperial1.cpp @@ -261,7 +261,7 @@ QString UnitsSchemaImperialBuilding::schemaTranslate(const Quantity& quant, // Process into string. Start with negative sign if quantity is less // than zero - char plusOrMinus; + char plusOrMinus {}; if (quant.getValue() < 0) { output << "-"; plusOrMinus = '-'; diff --git a/src/Base/Uuid.h b/src/Base/Uuid.h index 27297a6e11..8e7c080524 100644 --- a/src/Base/Uuid.h +++ b/src/Base/Uuid.h @@ -43,7 +43,9 @@ public: /// Construction Uuid(); Uuid(const Uuid&) = default; + Uuid(Uuid&&) = default; Uuid& operator=(const Uuid&) = default; + Uuid& operator=(Uuid&&) = default; /// Destruction virtual ~Uuid(); diff --git a/src/Base/Vector3D.cpp b/src/Base/Vector3D.cpp index 2d0711ed28..16574df72c 100644 --- a/src/Base/Vector3D.cpp +++ b/src/Base/Vector3D.cpp @@ -23,6 +23,7 @@ #include "PreCompiled.h" +#include #include #include "Vector3D.h" @@ -215,9 +216,9 @@ bool Vector3<_Precision>::operator!=(const Vector3<_Precision>& rcVct) const template bool Vector3<_Precision>::operator==(const Vector3<_Precision>& rcVct) const { - return (fabs(x - rcVct.x) <= traits_type::epsilon()) - && (fabs(y - rcVct.y) <= traits_type::epsilon()) - && (fabs(z - rcVct.z) <= traits_type::epsilon()); + return (std::fabs(x - rcVct.x) <= traits_type::epsilon()) + && (std::fabs(y - rcVct.y) <= traits_type::epsilon()) + && (std::fabs(z - rcVct.z) <= traits_type::epsilon()); } template @@ -254,15 +255,16 @@ _Precision Vector3<_Precision>::DistanceToPlane(const Vector3<_Precision>& rclBa template _Precision Vector3<_Precision>::Length() const { - return static_cast<_Precision>(sqrt((x * x) + (y * y) + (z * z))); + return static_cast<_Precision>(std::sqrt((x * x) + (y * y) + (z * z))); } template -_Precision Vector3<_Precision>::DistanceToLine(const Vector3<_Precision>& rclBase, - const Vector3<_Precision>& rclDirect) const +_Precision Vector3<_Precision>::DistanceToLine(const Vector3<_Precision>& base, + const Vector3<_Precision>& dir) const { - return static_cast<_Precision>( - fabs((rclDirect % Vector3(*this - rclBase)).Length() / rclDirect.Length())); + // clang-format off + return static_cast<_Precision>(std::fabs((dir % Vector3(*this - base)).Length() / dir.Length())); + // clang-format on } template @@ -367,10 +369,9 @@ template void Vector3<_Precision>::RotateX(_Precision f) { Vector3 cPt(*this); - _Precision fsin, fcos; - fsin = static_cast<_Precision>(sin(f)); - fcos = static_cast<_Precision>(cos(f)); + _Precision fsin = static_cast<_Precision>(sin(f)); + _Precision fcos = static_cast<_Precision>(cos(f)); y = (cPt.y * fcos) - (cPt.z * fsin); z = (cPt.y * fsin) + (cPt.z * fcos); } @@ -379,10 +380,9 @@ template void Vector3<_Precision>::RotateY(_Precision f) { Vector3 cPt(*this); - _Precision fsin, fcos; - fsin = static_cast<_Precision>(sin(f)); - fcos = static_cast<_Precision>(cos(f)); + _Precision fsin = static_cast<_Precision>(sin(f)); + _Precision fcos = static_cast<_Precision>(cos(f)); x = (cPt.z * fsin) + (cPt.x * fcos); z = (cPt.z * fcos) - (cPt.x * fsin); } @@ -391,10 +391,9 @@ template void Vector3<_Precision>::RotateZ(_Precision f) { Vector3 cPt(*this); - _Precision fsin, fcos; - fsin = static_cast<_Precision>(sin(f)); - fcos = static_cast<_Precision>(cos(f)); + _Precision fsin = static_cast<_Precision>(sin(f)); + _Precision fcos = static_cast<_Precision>(cos(f)); x = (cPt.x * fcos) - (cPt.y * fsin); y = (cPt.x * fsin) + (cPt.y * fcos); } @@ -434,7 +433,7 @@ _Precision Vector3<_Precision>::GetAngle(const Vector3& rcVect) const if (dot <= -1.0) { return traits_type::pi(); } - else if (dot >= 1.0) { + if (dot >= 1.0) { return 0.0; } @@ -446,7 +445,10 @@ void Vector3<_Precision>::TransformToCoordinateSystem(const Vector3& rclBase, const Vector3& rclDirX, const Vector3& rclDirY) { - Vector3 clVectX, clVectY, clVectZ, clVectOld; + Vector3 clVectX; + Vector3 clVectY; + Vector3 clVectZ; + Vector3 clVectOld; clVectX = rclDirX; clVectY = rclDirY; diff --git a/src/Base/Vector3D.h b/src/Base/Vector3D.h index 5cf75b9595..e0c14dab98 100644 --- a/src/Base/Vector3D.h +++ b/src/Base/Vector3D.h @@ -118,7 +118,7 @@ public: /// Construction explicit Vector3(_Precision fx = 0.0, _Precision fy = 0.0, _Precision fz = 0.0); Vector3(const Vector3<_Precision>& v) = default; - Vector3(Vector3<_Precision>&& v) = default; + Vector3(Vector3<_Precision>&& v) noexcept = default; ~Vector3() = default; /** @name Operator */ @@ -145,7 +145,7 @@ public: Vector3& operator/=(_Precision fDiv); /// Assignment Vector3& operator=(const Vector3<_Precision>& v) = default; - Vector3& operator=(Vector3<_Precision>&& v) = default; + Vector3& operator=(Vector3<_Precision>&& v) noexcept = default; /// Scalar product _Precision operator*(const Vector3<_Precision>& rcVct) const; /// Scalar product @@ -253,7 +253,9 @@ public: template inline _Precision Distance(const Vector3<_Precision>& v1, const Vector3<_Precision>& v2) { - _Precision x = v1.x - v2.x, y = v1.y - v2.y, z = v1.z - v2.z; + _Precision x = v1.x - v2.x; + _Precision y = v1.y - v2.y; + _Precision z = v1.z - v2.z; return static_cast<_Precision>(sqrt((x * x) + (y * y) + (z * z))); } @@ -261,7 +263,9 @@ inline _Precision Distance(const Vector3<_Precision>& v1, const Vector3<_Precisi template inline _Precision DistanceP2(const Vector3<_Precision>& v1, const Vector3<_Precision>& v2) { - _Precision x = v1.x - v2.x, y = v1.y - v2.y, z = v1.z - v2.z; + _Precision x = v1.x - v2.x; + _Precision y = v1.y - v2.y; + _Precision z = v1.z - v2.z; return x * x + y * y + z * z; } @@ -272,10 +276,10 @@ inline Vector3<_Precision> operator*(_Precision fFac, const Vector3<_Precision>& return Vector3<_Precision>(rcVct.x * fFac, rcVct.y * fFac, rcVct.z * fFac); } -template -inline Vector3<_Pr1> toVector(const Vector3<_Pr2>& v) +template +inline Vector3 toVector(const Vector3& v) { - return Vector3<_Pr1>(static_cast<_Pr1>(v.x), static_cast<_Pr1>(v.y), static_cast<_Pr1>(v.z)); + return Vector3(static_cast(v.x), static_cast(v.y), static_cast(v.z)); } using Vector3f = Vector3; diff --git a/src/Base/VectorPyImp.cpp b/src/Base/VectorPyImp.cpp index 5ce642fbf7..fb08d09def 100644 --- a/src/Base/VectorPyImp.cpp +++ b/src/Base/VectorPyImp.cpp @@ -52,7 +52,7 @@ std::string VectorPy::representation() const return str.str(); } -PyObject* VectorPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python wrapper +PyObject* VectorPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/) { // create a new instance of VectorPy and the Twin object return new VectorPy(new Vector3d); @@ -61,7 +61,9 @@ PyObject* VectorPy::PyMake(struct _typeobject*, PyObject*, PyObject*) // Python // constructor method int VectorPy::PyInit(PyObject* args, PyObject* /*kwd*/) { - double x = 0.0, y = 0.0, z = 0.0; + double x = 0.0; + double y = 0.0; + double z = 0.0; PyObject* object = nullptr; VectorPy::PointerType ptr = getVectorPtr(); if (PyArg_ParseTuple(args, "|ddd", &x, &y, &z)) { @@ -174,7 +176,7 @@ PyObject* VectorPy::number_multiply_handler(PyObject* self, PyObject* other) } } -Py_ssize_t VectorPy::sequence_length(PyObject*) +Py_ssize_t VectorPy::sequence_length(PyObject* /*unused*/) { return 3; } @@ -242,7 +244,12 @@ PyObject* VectorPy::mapping_subscript(PyObject* self, PyObject* item) return sequence_item(self, i); } else if (PySlice_Check(item)) { - Py_ssize_t start = 0, stop = 0, step = 0, slicelength = 0, cur = 0, i = 0; + Py_ssize_t start = 0; + Py_ssize_t stop = 0; + Py_ssize_t step = 0; + Py_ssize_t slicelength = 0; + Py_ssize_t cur = 0; + Py_ssize_t i = 0; PyObject* slice = item; if (PySlice_GetIndicesEx(slice, sequence_length(self), &start, &stop, &step, &slicelength) @@ -372,7 +379,9 @@ PyObject* VectorPy::isEqual(PyObject* args) PyObject* VectorPy::scale(PyObject* args) { - double factorX = 0.0, factorY = 0.0, factorZ = 0.0; + double factorX = 0.0; + double factorY = 0.0; + double factorZ = 0.0; if (!PyArg_ParseTuple(args, "ddd", &factorX, &factorY, &factorZ)) { return nullptr; } @@ -428,7 +437,8 @@ PyObject* VectorPy::cross(PyObject* args) PyObject* VectorPy::isOnLineSegment(PyObject* args) { - PyObject *start = nullptr, *end = nullptr; + PyObject* start = nullptr; + PyObject* end = nullptr; if (!PyArg_ParseTuple(args, "OO", &start, &end)) { return nullptr; } @@ -487,7 +497,8 @@ PyObject* VectorPy::normalize(PyObject* args) PyObject* VectorPy::projectToLine(PyObject* args) { - PyObject *base = nullptr, *line = nullptr; + PyObject* base = nullptr; + PyObject* line = nullptr; if (!PyArg_ParseTuple(args, "OO", &base, &line)) { return nullptr; } @@ -514,7 +525,8 @@ PyObject* VectorPy::projectToLine(PyObject* args) PyObject* VectorPy::projectToPlane(PyObject* args) { - PyObject *base = nullptr, *line = nullptr; + PyObject* base = nullptr; + PyObject* line = nullptr; if (!PyArg_ParseTuple(args, "OO", &base, &line)) { return nullptr; } @@ -556,7 +568,8 @@ PyObject* VectorPy::distanceToPoint(PyObject* args) PyObject* VectorPy::distanceToLine(PyObject* args) { - PyObject *base = nullptr, *line = nullptr; + PyObject* base = nullptr; + PyObject* line = nullptr; if (!PyArg_ParseTuple(args, "OO", &base, &line)) { return nullptr; } @@ -582,7 +595,8 @@ PyObject* VectorPy::distanceToLine(PyObject* args) PyObject* VectorPy::distanceToLineSegment(PyObject* args) { - PyObject *base = nullptr, *line = nullptr; + PyObject* base = nullptr; + PyObject* line = nullptr; if (!PyArg_ParseTuple(args, "OO", &base, &line)) { return nullptr; } @@ -608,7 +622,8 @@ PyObject* VectorPy::distanceToLineSegment(PyObject* args) PyObject* VectorPy::distanceToPlane(PyObject* args) { - PyObject *base = nullptr, *line = nullptr; + PyObject* base = nullptr; + PyObject* line = nullptr; if (!PyArg_ParseTuple(args, "OO", &base, &line)) { return nullptr; } diff --git a/src/Base/ViewProj.cpp b/src/Base/ViewProj.cpp index ff71b5950b..c679e9a46c 100644 --- a/src/Base/ViewProj.cpp +++ b/src/Base/ViewProj.cpp @@ -120,11 +120,11 @@ void perspectiveTransform(const Base::Matrix4D& mat, Vec& pnt) double m31 = mat[3][1]; double m32 = mat[3][2]; double m33 = mat[3][3]; - double w = (static_cast(pnt.x) * m30 + static_cast(pnt.y) * m31 - + static_cast(pnt.z) * m32 + m33); + double ww = (static_cast(pnt.x) * m30 + static_cast(pnt.y) * m31 + + static_cast(pnt.z) * m32 + m33); mat.multVec(pnt, pnt); - pnt /= static_cast(w); + pnt /= static_cast(ww); } Vector3f ViewProjMatrix::operator()(const Vector3f& inp) const @@ -136,7 +136,7 @@ Vector3f ViewProjMatrix::operator()(const Vector3f& inp) const if (!isOrthographic) { dst = src; perspectiveTransform(_clMtx, dst); - dst.Set(0.5f * dst.x + 0.5f, 0.5f * dst.y + 0.5f, 0.5f * dst.z + 0.5f); + dst.Set(0.5F * dst.x + 0.5F, 0.5F * dst.y + 0.5F, 0.5F * dst.z + 0.5F); } else { _clMtx.multVec(src, dst); @@ -167,7 +167,7 @@ Vector3f ViewProjMatrix::inverse(const Vector3f& src) const { Vector3f dst; if (!isOrthographic) { - dst.Set(2.0f * src.x - 1.0f, 2.0f * src.y - 1.0f, 2.0f * src.z - 1.0f); + dst.Set(2.0F * src.x - 1.0F, 2.0F * src.y - 1.0F, 2.0F * src.z - 1.0F); perspectiveTransform(_clMtxInv, dst); } else { diff --git a/src/Base/ViewProj.h b/src/Base/ViewProj.h index 846972cd4d..1788289714 100644 --- a/src/Base/ViewProj.h +++ b/src/Base/ViewProj.h @@ -38,7 +38,9 @@ class BaseExport ViewProjMethod { public: ViewProjMethod(const ViewProjMethod&) = default; + ViewProjMethod(ViewProjMethod&&) = default; ViewProjMethod& operator=(const ViewProjMethod&) = default; + ViewProjMethod& operator=(ViewProjMethod&&) = default; virtual ~ViewProjMethod() = default; virtual bool isValid() const; @@ -80,14 +82,14 @@ class BaseExport ViewProjMatrix: public ViewProjMethod public: ViewProjMatrix(const Matrix4D& rclMtx); - Vector3f operator()(const Vector3f& rclPt) const override; - Vector3d operator()(const Vector3d& rclPt) const override; - Vector3f inverse(const Vector3f& rclPt) const override; - Vector3d inverse(const Vector3d& rclPt) const override; + Vector3f operator()(const Vector3f& inp) const override; + Vector3d operator()(const Vector3d& inp) const override; + Vector3f inverse(const Vector3f& src) const override; + Vector3d inverse(const Vector3d& src) const override; Matrix4D getProjectionMatrix() const override; -protected: +private: bool isOrthographic; Matrix4D _clMtx, _clMtxInv; }; @@ -110,7 +112,7 @@ public: Matrix4D getProjectionMatrix() const override; -protected: +private: Matrix4D _clMtx, _clMtxInv; }; diff --git a/src/Base/Writer.cpp b/src/Base/Writer.cpp index 422b3ad6b9..24901d94fa 100644 --- a/src/Base/Writer.cpp +++ b/src/Base/Writer.cpp @@ -51,12 +51,12 @@ struct cdata_filter using category = boost::iostreams::output_filter_tag; template - inline bool put(Device& dev, char c) + inline bool put(Device& dev, char ch) { switch (state) { case 0: case 1: - if (c == ']') { + if (ch == ']') { ++state; } else { @@ -64,14 +64,14 @@ struct cdata_filter } break; case 2: - if (c == '>') { + if (ch == '>') { static const char escape[] = "]]> bytes(static_cast(fileSize)); // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - from.read(reinterpret_cast(&bytes[0]), fileSize); - Stream() << Base::base64_encode(&bytes[0], static_cast(fileSize)); + from.read(reinterpret_cast(bytes.data()), fileSize); + Stream() << Base::base64_encode(bytes.data(), static_cast(fileSize)); Stream() << "]]>" << endl; } @@ -172,14 +172,14 @@ void Writer::setForceXML(bool on) forceXML = on; } -bool Writer::isForceXML() +bool Writer::isForceXML() const { return forceXML; } -void Writer::setFileVersion(int v) +void Writer::setFileVersion(int version) { - fileVersion = v; + fileVersion = version; } int Writer::getFileVersion() const @@ -269,26 +269,27 @@ std::string Writer::getUniqueFileName(const char* Name) // if not, name is OK return CleanName; } - else { - std::vector names; - names.reserve(FileNames.size()); - FileInfo fi(CleanName); - CleanName = fi.fileNamePure(); - std::string ext = fi.extension(); - for (pos = FileNames.begin(); pos != FileNames.end(); ++pos) { - fi.setFile(*pos); - std::string FileName = fi.fileNamePure(); - if (fi.extension() == ext) { - names.push_back(FileName); - } + + std::vector names; + names.reserve(FileNames.size()); + FileInfo fi(CleanName); + CleanName = fi.fileNamePure(); + std::string ext = fi.extension(); + for (pos = FileNames.begin(); pos != FileNames.end(); ++pos) { + fi.setFile(*pos); + std::string FileName = fi.fileNamePure(); + if (fi.extension() == ext) { + names.push_back(FileName); } - std::stringstream str; - str << Base::Tools::getUniqueName(CleanName, names); - if (!ext.empty()) { - str << "." << ext; - } - return str.str(); } + + std::stringstream str; + str << Base::Tools::getUniqueName(CleanName, names); + if (!ext.empty()) { + str << "." << ext; + } + + return str.str(); } const std::vector& Writer::getFilenames() const @@ -377,7 +378,7 @@ void FileWriter::putNextEntry(const char* file) this->FileStream.open(fileName.c_str(), std::ios::out | std::ios::binary); } -bool FileWriter::shouldWrite(const std::string&, const Base::Persistence*) const +bool FileWriter::shouldWrite(const std::string& /*name*/, const Base::Persistence* /*obj*/) const { return true; } diff --git a/src/Base/Writer.h b/src/Base/Writer.h index 27684e4b4f..63bbdfcd37 100644 --- a/src/Base/Writer.h +++ b/src/Base/Writer.h @@ -64,7 +64,7 @@ public: /// switch the writer in XML only mode (no files allowed) void setForceXML(bool on); /// check on state - bool isForceXML(); + bool isForceXML() const; void setFileVersion(int); int getFileVersion() const; @@ -73,7 +73,7 @@ public: /// insert a binary file BASE64 coded as CDATA section in the XML file void insertBinFile(const char* FileName); /// insert text string as CDATA - void insertText(const std::string& s); + void insertText(const std::string& str); /** @name additional file writing */ //@{ @@ -143,6 +143,7 @@ public: /// Return the current character output stream std::ostream& charStream(); + // NOLINTBEGIN /// name for underlying file saves std::string ObjectName; @@ -163,10 +164,13 @@ protected: bool forceXML {false}; int fileVersion {1}; + // NOLINTEND public: Writer(const Writer&) = delete; + Writer(Writer&&) = delete; Writer& operator=(const Writer&) = delete; + Writer& operator=(Writer&&) = delete; private: std::unique_ptr CharStream; @@ -207,6 +211,11 @@ public: ZipStream.putNextEntry(str); } + ZipWriter(const ZipWriter&) = delete; + ZipWriter(ZipWriter&&) = delete; + ZipWriter& operator=(const ZipWriter&) = delete; + ZipWriter& operator=(ZipWriter&&) = delete; + private: zipios::ZipOutputStream ZipStream; }; @@ -265,9 +274,16 @@ public: */ virtual bool shouldWrite(const std::string& name, const Base::Persistence* Object) const; + FileWriter(const FileWriter&) = delete; + FileWriter(FileWriter&&) = delete; + FileWriter& operator=(const FileWriter&) = delete; + FileWriter& operator=(FileWriter&&) = delete; + protected: + // NOLINTBEGIN std::string DirName; std::ofstream FileStream; + // NOLINTEND }; diff --git a/src/Base/XMLTools.cpp b/src/Base/XMLTools.cpp index 2fec3b5e3d..a9f780e407 100644 --- a/src/Base/XMLTools.cpp +++ b/src/Base/XMLTools.cpp @@ -32,7 +32,7 @@ std::unique_ptr XMLTools::transcoder; void XMLTools::initialize() { - if (!transcoder.get()) { + if (!transcoder) { XMLTransService::Codes res {}; transcoder.reset(XMLPlatformUtils::fgTransService->makeNewTranscoderFor( XMLRecognizer::UTF_8, diff --git a/src/Base/XMLTools.h b/src/Base/XMLTools.h index 2cc046b2d1..80bbc975f0 100644 --- a/src/Base/XMLTools.h +++ b/src/Base/XMLTools.h @@ -48,7 +48,7 @@ public: static void terminate(); private: - static std::unique_ptr transcoder; + static std::unique_ptr transcoder; // NOLINT }; //************************************************************************** @@ -64,6 +64,7 @@ public: /// Getter method const char* c_str() const; + FC_DISABLE_COPY_MOVE(StrX) private: // This is the local code page form of the string. @@ -143,12 +144,12 @@ class XStr public: /// Constructors and Destructor XStr(const char* const toTranscode); - /// ~XStr(); /// Getter method const XMLCh* unicodeForm() const; + FC_DISABLE_COPY_MOVE(XStr) private: /// This is the Unicode XMLCh format of the string. @@ -189,6 +190,8 @@ public: /// Getter method const XMLCh* unicodeForm() const; + FC_DISABLE_COPY_MOVE(XUTF8Str) + private: std::basic_string str; }; diff --git a/src/Base/ZipHeader.cpp b/src/Base/ZipHeader.cpp index b0660eaad8..b3273810d5 100644 --- a/src/Base/ZipHeader.cpp +++ b/src/Base/ZipHeader.cpp @@ -68,12 +68,11 @@ std::istream* ZipHeader::getInputStream(const std::string& entry_name, MatchPath if (!ent) { return nullptr; } - else { - return new zipios::ZipInputStream( - _input, - static_cast(ent.get())->getLocalHeaderOffset() - + _vs.startOffset()); - } + + return new zipios::ZipInputStream( + _input, + static_cast(ent.get())->getLocalHeaderOffset() + + _vs.startOffset()); } bool ZipHeader::init(std::istream& _zipfile) @@ -110,11 +109,11 @@ bool ZipHeader::readCentralDirectory(std::istream& _zipfile) throw zipios::IOException( "Error reading zip file while reading zip file central directory"); } - else if (_zipfile.fail()) { + if (_zipfile.fail()) { throw zipios::FCollException("Zip file consistency problem. Failure while reading " "zip file central directory"); } - else if (_zipfile.eof()) { + if (_zipfile.eof()) { throw zipios::IOException( "Premature end of file while reading zip file central directory"); } diff --git a/src/Base/ZipHeader.h b/src/Base/ZipHeader.h index c450c58004..8c9e58dbe8 100644 --- a/src/Base/ZipHeader.h +++ b/src/Base/ZipHeader.h @@ -57,8 +57,6 @@ public: /** Create a copy of this instance. */ FileCollection* clone() const override; - ~ZipHeader() override = default; - void close() override; std::istream* getInputStream(const ConstEntryPointer& entry) override; diff --git a/src/FCGlobal.h b/src/FCGlobal.h index 6e0e5ccf54..9501af4a52 100644 --- a/src/FCGlobal.h +++ b/src/FCGlobal.h @@ -59,4 +59,34 @@ # define GuiExport FREECAD_DECL_IMPORT #endif +// Disable copy/move +#define FC_DISABLE_COPY(Class) \ + Class(const Class &) = delete;\ + Class &operator=(const Class &) = delete; + +#define FC_DISABLE_MOVE(Class) \ + Class(Class &&) = delete; \ + Class &operator=(Class &&) = delete; + +#define FC_DISABLE_COPY_MOVE(Class) \ + FC_DISABLE_COPY(Class) \ + FC_DISABLE_MOVE(Class) + +// Default copy/move +#define FC_DEFAULT_COPY(Class) \ + Class(const Class &) = default;\ + Class &operator=(const Class &) = default; + +#define FC_DEFAULT_MOVE(Class) \ + Class(Class &&) = default; \ + Class &operator=(Class &&) = default; + +#define FC_DEFAULT_COPY_MOVE(Class) \ + FC_DEFAULT_COPY(Class) \ + FC_DEFAULT_MOVE(Class) + +#ifndef Q_DISABLE_COPY_MOVE +#define Q_DISABLE_COPY_MOVE FC_DEFAULT_COPY_MOVE +#endif + #endif //FC_GLOBAL_H