From eee122173875c1257c20603bec88c336a99a13f8 Mon Sep 17 00:00:00 2001 From: chrchr-github <78114321+chrchr-github@users.noreply.github.com> Date: Tue, 8 Aug 2023 11:05:02 +0200 Subject: [PATCH] Use in-class initializers, default constructors, class -> struct (#4842) --- .clang-tidy | 66 +++++++- clang-tidy.md | 8 +- cli/cmdlineparser.cpp | 4 - cli/cmdlineparser.h | 8 +- cli/cppcheckexecutor.cpp | 4 - cli/cppcheckexecutor.h | 10 +- cli/threadexecutor.cpp | 10 +- gui/applicationlist.cpp | 3 +- gui/applicationlist.h | 2 +- gui/checkthread.cpp | 4 +- gui/checkthread.h | 4 +- gui/codeeditorstyle.cpp | 1 - gui/codeeditorstyle.h | 2 +- gui/codeeditstylecontrols.cpp | 3 +- gui/codeeditstylecontrols.h | 2 +- gui/cppchecklibrarydata.h | 83 +++------- gui/helpdialog.h | 4 +- gui/librarydialog.cpp | 3 +- gui/librarydialog.h | 2 +- gui/mainwindow.cpp | 6 +- gui/mainwindow.h | 8 +- gui/report.cpp | 1 - gui/resultstree.cpp | 14 +- gui/resultstree.h | 24 +-- gui/resultsview.cpp | 1 - gui/resultsview.h | 2 +- gui/statsdialog.cpp | 3 +- gui/statsdialog.h | 2 +- gui/test/projectfile/testprojectfile.cpp | 3 +- gui/threadhandler.cpp | 6 +- gui/threadhandler.h | 6 +- gui/threadresult.cpp | 5 - gui/threadresult.h | 10 +- gui/translationhandler.cpp | 3 +- gui/translationhandler.h | 2 +- lib/analyzer.h | 4 +- lib/check.cpp | 2 +- lib/check.h | 6 +- lib/checkclass.h | 10 +- lib/checkio.cpp | 19 +-- lib/checkio.h | 16 +- lib/checkuninitvar.h | 4 +- lib/checkunusedfunctions.h | 11 +- lib/checkunusedvar.cpp | 2 +- lib/clangimport.cpp | 18 +-- lib/cppcheck.cpp | 3 - lib/cppcheck.h | 6 +- lib/ctu.cpp | 2 - lib/forwardanalyzer.cpp | 8 +- lib/fwdanalysis.h | 14 +- lib/importproject.cpp | 4 +- lib/importproject.h | 7 +- lib/library.cpp | 3 - lib/library.h | 147 ++++++----------- lib/mathlib.cpp | 3 +- lib/mathlib.h | 6 +- lib/programmemory.cpp | 2 +- lib/settings.cpp | 38 ----- lib/settings.h | 103 ++++++------ lib/standards.h | 7 +- lib/suppressions.h | 14 +- lib/symboldatabase.cpp | 57 +------ lib/symboldatabase.h | 191 ++++++++--------------- lib/templatesimplifier.cpp | 2 +- lib/templatesimplifier.h | 2 +- lib/timer.cpp | 3 - lib/timer.h | 16 +- lib/token.cpp | 7 +- lib/token.h | 92 +++++------ lib/tokenize.cpp | 27 ++-- lib/tokenize.h | 10 +- lib/tokenlist.cpp | 19 +-- lib/tokenlist.h | 6 +- lib/valueflow.cpp | 75 ++++----- lib/valueflow.h | 12 +- lib/vfvalue.cpp | 21 +-- lib/vfvalue.h | 61 +++----- test/fixture.cpp | 5 +- test/fixture.h | 4 +- test/testtoken.cpp | 4 +- 80 files changed, 531 insertions(+), 861 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index 95710ddfb..fc451fb3c 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,5 +1,69 @@ --- -Checks: '*,-abseil-*,-altera-*,-android-*,-boost-*,-cert-*,-cppcoreguidelines-*,-darwin-*,-fuchsia-*,-google-*,-hicpp-*,-linuxkernel-*,-llvm-*,-llvmlibc-*,-mpi-*,-objc-*,-openmp-*,-zircon-*,google-explicit-constructor,-readability-braces-around-statements,-readability-magic-numbers,-bugprone-macro-parentheses,-readability-isolate-declaration,-readability-function-size,-modernize-use-trailing-return-type,-readability-implicit-bool-conversion,-readability-uppercase-literal-suffix,-modernize-use-auto,-modernize-use-default-member-init,-readability-redundant-member-init,-modernize-avoid-c-arrays,-modernize-use-equals-default,-readability-container-size-empty,-bugprone-branch-clone,-bugprone-narrowing-conversions,-modernize-raw-string-literal,-readability-convert-member-functions-to-static,-modernize-loop-convert,-readability-const-return-type,-modernize-return-braced-init-list,-performance-inefficient-string-concatenation,-misc-throw-by-value-catch-by-reference,-readability-avoid-const-params-in-decls,-misc-non-private-member-variables-in-classes,-clang-analyzer-*,-bugprone-signed-char-misuse,-misc-no-recursion,-readability-use-anyofallof,-performance-no-automatic-move,-readability-function-cognitive-complexity,-readability-redundant-access-specifiers,-concurrency-mt-unsafe,-bugprone-easily-swappable-parameters,-readability-suspicious-call-argument,-readability-identifier-length,-readability-container-data-pointer,-bugprone-assignment-in-if-condition,-misc-const-correctness,-portability-std-allocator-const,-modernize-deprecated-ios-base-aliases,-bugprone-unchecked-optional-access,-modernize-replace-auto-ptr,-readability-identifier-naming,-portability-simd-intrinsics,-misc-use-anonymous-namespace,cert-err34-c' +Checks: > + *, + -abseil-*, + -altera-*, + -android-*, + -boost-*, + -cert-*, + -cppcoreguidelines-*, + -darwin-*, + -fuchsia-*, + -google-*, + -hicpp-*, + -linuxkernel-*, + -llvm-*, + -llvmlibc-*, + -mpi-*, + -objc-*, + -openmp-*, + -zircon-*, + cert-err34-c, + google-explicit-constructor, + -bugprone-assignment-in-if-condition, + -bugprone-branch-clone, + -bugprone-easily-swappable-parameters, + -bugprone-macro-parentheses, + -bugprone-narrowing-conversions, + -bugprone-signed-char-misuse, + -bugprone-unchecked-optional-access, + -clang-analyzer-*, + -concurrency-mt-unsafe, + -misc-const-correctness, + -misc-no-recursion, + -misc-non-private-member-variables-in-classes, + -misc-throw-by-value-catch-by-reference, + -misc-use-anonymous-namespace, + -modernize-avoid-c-arrays, + -modernize-deprecated-ios-base-aliases, + -modernize-loop-convert, + -modernize-raw-string-literal, + -modernize-replace-auto-ptr, + -modernize-return-braced-init-list, + -modernize-use-auto, + -modernize-use-equals-default, + -modernize-use-trailing-return-type, + -performance-inefficient-string-concatenation, + -performance-no-automatic-move, + -portability-simd-intrinsics, + -portability-std-allocator-const, + -readability-avoid-const-params-in-decls, + -readability-braces-around-statements, + -readability-const-return-type, + -readability-container-data-pointer, + -readability-container-size-empty, + -readability-convert-member-functions-to-static, + -readability-function-cognitive-complexity, + -readability-function-size, + -readability-identifier-length, + -readability-identifier-naming, + -readability-implicit-bool-conversion, + -readability-isolate-declaration, + -readability-magic-numbers, + -readability-redundant-access-specifiers, + -readability-suspicious-call-argument, + -readability-uppercase-literal-suffix, + -readability-use-anyofallof WarningsAsErrors: '*' HeaderFilterRegex: '(cli|gui|lib|oss-fuzz|test|triage)\/[a-z]+\.h' CheckOptions: diff --git a/clang-tidy.md b/clang-tidy.md index 8e6625081..8d1de3c83 100644 --- a/clang-tidy.md +++ b/clang-tidy.md @@ -37,18 +37,16 @@ These are coding guidelines we do not follow. Some of the checks might be explic `modernize-use-auto`
`readability-uppercase-literal-suffix`
`readability-else-after-return`
-`modernize-use-default-member-init`
`readability-identifier-length`
-These do not relect the style we are (currently) enforcing. +These do not reflect the style we are (currently) enforcing. `readability-function-size`
`readability-function-cognitive-complexity`
-We are not interesting in the size/complexity of a function. +We are not interested in the size/complexity of a function. `readability-magic-numbers`
-`readability-redundant-member-init`
These do not (always) increase readability. @@ -58,7 +56,7 @@ To be documented. `readability-implicit-bool-conversion`
-This does not appear not to be useful as it is reported on very common code. +This does not appear to be useful as it is reported on very common code. `bugprone-narrowing-conversions`
`performance-no-automatic-move`
diff --git a/cli/cmdlineparser.cpp b/cli/cmdlineparser.cpp index a77fc3369..92b5c6a0a 100644 --- a/cli/cmdlineparser.cpp +++ b/cli/cmdlineparser.cpp @@ -113,10 +113,6 @@ CmdLineParser::CmdLineParser(Settings &settings, Suppressions &suppressions, Sup : mSettings(settings) , mSuppressions(suppressions) , mSuppressionsNoFail(suppressionsNoFail) - , mShowHelp(false) - , mShowVersion(false) - , mShowErrorMessages(false) - , mExitAfterPrint(false) {} void CmdLineParser::printMessage(const std::string &message) diff --git a/cli/cmdlineparser.h b/cli/cmdlineparser.h index e84e68352..2cd5df1cd 100644 --- a/cli/cmdlineparser.h +++ b/cli/cmdlineparser.h @@ -146,10 +146,10 @@ private: Settings &mSettings; Suppressions &mSuppressions; Suppressions &mSuppressionsNoFail; - bool mShowHelp; - bool mShowVersion; - bool mShowErrorMessages; - bool mExitAfterPrint; + bool mShowHelp{}; + bool mShowVersion{}; + bool mShowErrorMessages{}; + bool mExitAfterPrint{}; std::string mVSConfig; }; diff --git a/cli/cppcheckexecutor.cpp b/cli/cppcheckexecutor.cpp index 30ed27a0e..38c365d17 100644 --- a/cli/cppcheckexecutor.cpp +++ b/cli/cppcheckexecutor.cpp @@ -72,10 +72,6 @@ /*static*/ FILE* CppCheckExecutor::mExceptionOutput = stdout; -CppCheckExecutor::CppCheckExecutor() - : mSettings(nullptr), mLatestProgressOutputTime(0), mErrorOutput(nullptr), mShowAllErrors(false) -{} - CppCheckExecutor::~CppCheckExecutor() { delete mErrorOutput; diff --git a/cli/cppcheckexecutor.h b/cli/cppcheckexecutor.h index 1e94aa58d..9b73eb5d7 100644 --- a/cli/cppcheckexecutor.h +++ b/cli/cppcheckexecutor.h @@ -46,7 +46,7 @@ public: /** * Constructor */ - CppCheckExecutor(); + CppCheckExecutor() = default; CppCheckExecutor(const CppCheckExecutor &) = delete; void operator=(const CppCheckExecutor&) = delete; @@ -154,7 +154,7 @@ private: /** * Pointer to current settings; set while check() is running for reportError(). */ - const Settings* mSettings; + const Settings* mSettings{}; /** * Used to filter out duplicate error messages. @@ -169,7 +169,7 @@ private: /** * Report progress time */ - std::time_t mLatestProgressOutputTime; + std::time_t mLatestProgressOutputTime{}; /** * Output file name for exception handler @@ -179,12 +179,12 @@ private: /** * Error output */ - std::ofstream *mErrorOutput; + std::ofstream* mErrorOutput{}; /** * Has --errorlist been given? */ - bool mShowAllErrors; + bool mShowAllErrors{}; }; #endif // CPPCHECKEXECUTOR_H diff --git a/cli/threadexecutor.cpp b/cli/threadexecutor.cpp index 8590651a2..a6a9e671b 100644 --- a/cli/threadexecutor.cpp +++ b/cli/threadexecutor.cpp @@ -85,7 +85,7 @@ class ThreadData { public: ThreadData(ThreadExecutor &threadExecutor, ErrorLogger &errorLogger, const Settings &settings, const std::map &files, const std::list &fileSettings) - : mFiles(files), mFileSettings(fileSettings), mProcessedFiles(0), mProcessedSize(0), mSettings(settings), logForwarder(threadExecutor, errorLogger) + : mFiles(files), mFileSettings(fileSettings), mSettings(settings), logForwarder(threadExecutor, errorLogger) { mItNextFile = mFiles.begin(); mItNextFileSettings = mFileSettings.begin(); @@ -148,10 +148,10 @@ private: const std::list &mFileSettings; std::list::const_iterator mItNextFileSettings; - std::size_t mProcessedFiles; - std::size_t mTotalFiles; - std::size_t mProcessedSize; - std::size_t mTotalFileSize; + std::size_t mProcessedFiles{}; + std::size_t mTotalFiles{}; + std::size_t mProcessedSize{}; + std::size_t mTotalFileSize{}; std::mutex mFileSync; const Settings &mSettings; diff --git a/gui/applicationlist.cpp b/gui/applicationlist.cpp index 03079b1d7..dde03718f 100644 --- a/gui/applicationlist.cpp +++ b/gui/applicationlist.cpp @@ -27,8 +27,7 @@ #include ApplicationList::ApplicationList(QObject *parent) : - QObject(parent), - mDefaultApplicationIndex(-1) + QObject(parent) { //ctor } diff --git a/gui/applicationlist.h b/gui/applicationlist.h index d7885a8bc..537ca51af 100644 --- a/gui/applicationlist.h +++ b/gui/applicationlist.h @@ -133,7 +133,7 @@ private: * @brief Index of the default application. * */ - int mDefaultApplicationIndex; + int mDefaultApplicationIndex = -1; }; /// @} #endif // APPLICATIONLIST_H diff --git a/gui/checkthread.cpp b/gui/checkthread.cpp index 480907a59..b45f30c6e 100644 --- a/gui/checkthread.cpp +++ b/gui/checkthread.cpp @@ -84,10 +84,8 @@ static bool executeCommand(std::string exe, std::vector args, std:: CheckThread::CheckThread(ThreadResult &result) : - mState(Ready), mResult(result), - mCppcheck(result, true, executeCommand), - mAnalyseWholeProgram(false) + mCppcheck(result, true, executeCommand) { //ctor } diff --git a/gui/checkthread.h b/gui/checkthread.h index 519d74923..9a1fea3e6 100644 --- a/gui/checkthread.h +++ b/gui/checkthread.h @@ -120,7 +120,7 @@ protected: /** * @brief Thread's current execution state. */ - State mState; + State mState = Ready; ThreadResult &mResult; /** @@ -136,7 +136,7 @@ private: bool isSuppressed(const Suppressions::ErrorMessage &errorMessage) const; QStringList mFiles; - bool mAnalyseWholeProgram; + bool mAnalyseWholeProgram{}; QStringList mAddonsAndTools; QStringList mClangIncludePaths; QList mSuppressions; diff --git a/gui/codeeditorstyle.cpp b/gui/codeeditorstyle.cpp index 85900d033..fc981ad40 100644 --- a/gui/codeeditorstyle.cpp +++ b/gui/codeeditorstyle.cpp @@ -42,7 +42,6 @@ CodeEditorStyle::CodeEditorStyle( // cppcheck-suppress naming-varname - TODO: fix this QColor SymbFGColor, QColor SymbBGColor, const QFont::Weight& SymbWeight) : - mSystemTheme(false), widgetFGColor(std::move(CtrlFGColor)), widgetBGColor(std::move(CtrlBGColor)), highlightBGColor(std::move(HiLiBGColor)), diff --git a/gui/codeeditorstyle.h b/gui/codeeditorstyle.h index aee3d028c..392602b9a 100644 --- a/gui/codeeditorstyle.h +++ b/gui/codeeditorstyle.h @@ -81,7 +81,7 @@ public: static void saveSettings(QSettings *settings, const CodeEditorStyle& theStyle); public: - bool mSystemTheme; + bool mSystemTheme{}; QColor widgetFGColor; QColor widgetBGColor; QColor highlightBGColor; diff --git a/gui/codeeditstylecontrols.cpp b/gui/codeeditstylecontrols.cpp index 186d76c1e..8cd4465c5 100644 --- a/gui/codeeditstylecontrols.cpp +++ b/gui/codeeditstylecontrols.cpp @@ -69,8 +69,7 @@ const QColor& SelectColorButton::getColor() } SelectFontWeightCombo::SelectFontWeightCombo(QWidget* parent) : - QComboBox(parent), - mWeight(QFont::Normal) + QComboBox(parent) { addItem(QObject::tr("Thin"), QVariant(static_cast(QFont::Thin))); diff --git a/gui/codeeditstylecontrols.h b/gui/codeeditstylecontrols.h index b624d0e8d..7e87c7b5f 100644 --- a/gui/codeeditstylecontrols.h +++ b/gui/codeeditstylecontrols.h @@ -71,7 +71,7 @@ public slots: void changeWeight(int index); private: - QFont::Weight mWeight; + QFont::Weight mWeight = QFont::Normal; }; #endif //CODEEDITORSTYLECONTROLS_H diff --git a/gui/cppchecklibrarydata.h b/gui/cppchecklibrarydata.h index e0360534e..252d66920 100644 --- a/gui/cppchecklibrarydata.h +++ b/gui/cppchecklibrarydata.h @@ -33,8 +33,6 @@ public: CppcheckLibraryData(); struct Container { - Container() : access_arrayLike(false), size_templateParameter(-1) {} - QString id; QString inherits; QString startPattern; @@ -42,8 +40,8 @@ public: QString opLessAllowed; QString itEndPattern; - bool access_arrayLike; - int size_templateParameter; + bool access_arrayLike{}; + int size_templateParameter = -1; struct { QString templateParameter; @@ -72,21 +70,17 @@ public: }; struct Function { - Function() : noreturn(Unknown), gccPure(false), gccConst(false), - leakignore(false), useretval(false) {} - QString comments; QString name; - enum TrueFalseUnknown { False, True, Unknown } noreturn; - bool gccPure; - bool gccConst; - bool leakignore; - bool useretval; + enum TrueFalseUnknown { False, True, Unknown } noreturn = Unknown; + bool gccPure{}; + bool gccConst{}; + bool leakignore{}; + bool useretval{}; struct ReturnValue { - ReturnValue() : container(-1) {} QString type; QString value; - int container; + int container = -1; bool empty() const { return type.isNull() && value.isNull() && container < 0; } @@ -96,19 +90,16 @@ public: QString secure; } formatstr; struct Arg { - Arg() : nr(0), notbool(false), notnull(false), notuninit(false), - formatstr(false), strz(false) {} - QString name; - unsigned int nr; + unsigned int nr{}; static const unsigned int ANY; static const unsigned int VARIADIC; QString defaultValue; - bool notbool; - bool notnull; - bool notuninit; - bool formatstr; - bool strz; + bool notbool{}; + bool notnull{}; + bool notuninit{}; + bool formatstr{}; + bool strz{}; QString valid; struct MinSize { QString type; @@ -117,8 +108,7 @@ public: }; QList minsizes; struct Iterator { - Iterator() : container(-1) {} - int container; + int container = -1; QString type; } iterator; }; @@ -147,26 +137,15 @@ public: struct MemoryResource { QString type; // "memory" or "resource" struct Alloc { - Alloc() : - isRealloc(false), - init(false), - arg(-1), // -1: Has no optional "arg" attribute - reallocArg(-1) // -1: Has no optional "realloc-arg" attribute - {} - - bool isRealloc; - bool init; - int arg; - int reallocArg; + bool isRealloc{}; + bool init{}; + int arg = -1; // -1: Has no optional "realloc-arg" attribute + int reallocArg = -1; // -1: Has no optional "arg" attribute QString bufferSize; QString name; }; struct Dealloc { - Dealloc() : - arg(-1) // -1: Has no optional "arg" attribute - {} - - int arg; + int arg = -1; // -1: Has no optional "arg" attribute QString name; }; @@ -193,11 +172,7 @@ public: struct Reflection { struct Call { - Call() : - arg {-1} // -1: Mandatory "arg" attribute not available - {} - - int arg; + int arg = -1; // -1: Mandatory "arg" attribute not available QString name; }; @@ -206,12 +181,8 @@ public: struct Markup { struct CodeBlocks { - CodeBlocks() : - offset {-1} - {} - QStringList blocks; - int offset; + int offset = -1; QString start; QString end; }; @@ -223,8 +194,8 @@ public: }; QString ext; - bool afterCode; - bool reportErrors; + bool afterCode{}; + bool reportErrors{}; QStringList keywords; QStringList importer; QList codeBlocks; @@ -232,12 +203,8 @@ public: }; struct SmartPointer { - SmartPointer() : - unique {false} - {} - QString name; - bool unique; + bool unique{}; }; struct Entrypoint { diff --git a/gui/helpdialog.h b/gui/helpdialog.h index a5dc0b430..075005fd8 100644 --- a/gui/helpdialog.h +++ b/gui/helpdialog.h @@ -34,7 +34,7 @@ namespace Ui { class HelpBrowser : public QTextBrowser { public: - explicit HelpBrowser(QWidget* parent = nullptr) : QTextBrowser(parent), mHelpEngine(nullptr) {} + explicit HelpBrowser(QWidget* parent = nullptr) : QTextBrowser(parent) {} HelpBrowser(const HelpBrowser&) = delete; HelpBrowser(HelpBrowser&&) = delete; HelpBrowser& operator=(const HelpBrowser&) = delete; @@ -42,7 +42,7 @@ public: void setHelpEngine(QHelpEngine *helpEngine); QVariant loadResource(int type, const QUrl& name) override; private: - QHelpEngine* mHelpEngine; + QHelpEngine* mHelpEngine{}; }; class HelpDialog : public QDialog { diff --git a/gui/librarydialog.cpp b/gui/librarydialog.cpp index e077a6b76..475456799 100644 --- a/gui/librarydialog.cpp +++ b/gui/librarydialog.cpp @@ -61,8 +61,7 @@ public: LibraryDialog::LibraryDialog(QWidget *parent) : QDialog(parent), - mUi(new Ui::LibraryDialog), - mIgnoreChanges(false) + mUi(new Ui::LibraryDialog) { mUi->setupUi(this); mUi->buttonSave->setEnabled(false); diff --git a/gui/librarydialog.h b/gui/librarydialog.h index d8dd3c247..ac27d4275 100644 --- a/gui/librarydialog.h +++ b/gui/librarydialog.h @@ -56,7 +56,7 @@ private: Ui::LibraryDialog *mUi; CppcheckLibraryData mData; QString mFileName; - bool mIgnoreChanges; + bool mIgnoreChanges{}; static QString getArgText(const CppcheckLibraryData::Function::Arg &arg); CppcheckLibraryData::Function *currentFunction(); diff --git a/gui/mainwindow.cpp b/gui/mainwindow.cpp index 814ec585d..2840c4833 100644 --- a/gui/mainwindow.cpp +++ b/gui/mainwindow.cpp @@ -109,14 +109,10 @@ MainWindow::MainWindow(TranslationHandler* th, QSettings* settings) : mApplications(new ApplicationList(this)), mTranslation(th), mUI(new Ui::MainWindow), - mScratchPad(nullptr), - mProjectFile(nullptr), mPlatformActions(new QActionGroup(this)), mCStandardActions(new QActionGroup(this)), mCppStandardActions(new QActionGroup(this)), - mSelectLanguageActions(new QActionGroup(this)), - mExiting(false), - mIsLogfileLoaded(false) + mSelectLanguageActions(new QActionGroup(this)) { { Settings tempSettings; diff --git a/gui/mainwindow.h b/gui/mainwindow.h index ab7d45d64..78782b22b 100644 --- a/gui/mainwindow.h +++ b/gui/mainwindow.h @@ -437,10 +437,10 @@ private: QString mCurrentDirectory; /** @brief Scratchpad. */ - ScratchPad* mScratchPad; + ScratchPad* mScratchPad{}; /** @brief Project (file). */ - ProjectFile *mProjectFile; + ProjectFile* mProjectFile{}; /** @brief Filter field in the Filter toolbar. */ QLineEdit* mLineEditFilter; @@ -462,10 +462,10 @@ private: * If this is true then the cppcheck is waiting for check threads to exit * so that the application can be closed. */ - bool mExiting; + bool mExiting{}; /** @brief Set to true in case of loading log file. */ - bool mIsLogfileLoaded; + bool mIsLogfileLoaded{}; /** * @brief Project MRU menu actions. diff --git a/gui/report.cpp b/gui/report.cpp index 9a4c391fd..e7b7e06ed 100644 --- a/gui/report.cpp +++ b/gui/report.cpp @@ -23,7 +23,6 @@ #include Report::Report(QString filename) : - QObject(), mFilename(std::move(filename)) {} diff --git a/gui/resultstree.cpp b/gui/resultstree.cpp index 241322c18..61f995e6b 100644 --- a/gui/resultstree.cpp +++ b/gui/resultstree.cpp @@ -81,19 +81,7 @@ static const int COLUMN_SINCE_DATE = 6; static const int COLUMN_TAGS = 7; ResultsTree::ResultsTree(QWidget * parent) : - QTreeView(parent), - mSettings(nullptr), - mApplications(nullptr), - mContextItem(nullptr), - mShowFullPath(false), - mSaveFullPath(false), - mSaveAllErrors(true), - mShowErrorId(false), - mVisibleErrors(false), - mSelectionModel(nullptr), - mThread(nullptr), - mShowCppcheck(true), - mShowClang(true) + QTreeView(parent) { setModel(&mModel); translate(); // Adds columns to grid diff --git a/gui/resultstree.h b/gui/resultstree.h index 1e67dca97..5828c0e38 100644 --- a/gui/resultstree.h +++ b/gui/resultstree.h @@ -453,7 +453,7 @@ protected: * @brief Program settings * */ - QSettings *mSettings; + QSettings* mSettings{}; /** * @brief A string used to filter the results for display. @@ -465,37 +465,37 @@ protected: * @brief List of applications to open errors with * */ - ApplicationList *mApplications; + ApplicationList* mApplications{}; /** * @brief Right clicked item (used by context menu slots) * */ - QStandardItem *mContextItem; + QStandardItem* mContextItem{}; /** * @brief Should full path of files be shown (true) or relative (false) * */ - bool mShowFullPath; + bool mShowFullPath{}; /** * @brief Should full path of files be saved * */ - bool mSaveFullPath; + bool mSaveFullPath{}; /** * @brief Save all errors (true) or only visible (false) * */ - bool mSaveAllErrors; + bool mSaveAllErrors = true; /** * @brief true if optional column "Id" is shown * */ - bool mShowErrorId; + bool mShowErrorId{}; /** * @brief Path we are currently checking @@ -507,7 +507,7 @@ protected: * @brief Are there any visible errors * */ - bool mVisibleErrors; + bool mVisibleErrors{}; private: /** tag selected items */ @@ -518,11 +518,11 @@ private: QStringList mHiddenMessageId; - QItemSelectionModel *mSelectionModel; - ThreadHandler *mThread; + QItemSelectionModel* mSelectionModel{}; + ThreadHandler *mThread{}; - bool mShowCppcheck; - bool mShowClang; + bool mShowCppcheck = true; + bool mShowClang = true; }; /// @} #endif // RESULTSTREE_H diff --git a/gui/resultsview.cpp b/gui/resultsview.cpp index 2ee37ae94..6c57e8c15 100644 --- a/gui/resultsview.cpp +++ b/gui/resultsview.cpp @@ -67,7 +67,6 @@ ResultsView::ResultsView(QWidget * parent) : QWidget(parent), - mShowNoErrorsMessage(true), mUI(new Ui::ResultsView), mStatistics(new CheckStatistics(this)) { diff --git a/gui/resultsview.h b/gui/resultsview.h index f07c58873..b44adfd07 100644 --- a/gui/resultsview.h +++ b/gui/resultsview.h @@ -344,7 +344,7 @@ protected: /** * @brief Should we show a "No errors found dialog" every time no errors were found? */ - bool mShowNoErrorsMessage; + bool mShowNoErrorsMessage = true; Ui::ResultsView *mUI; diff --git a/gui/statsdialog.cpp b/gui/statsdialog.cpp index 7b8db7ca6..4f5ce9a85 100644 --- a/gui/statsdialog.cpp +++ b/gui/statsdialog.cpp @@ -71,8 +71,7 @@ static const QString CPPCHECK("cppcheck"); StatsDialog::StatsDialog(QWidget *parent) : QDialog(parent), - mUI(new Ui::StatsDialog), - mStatistics(nullptr) + mUI(new Ui::StatsDialog) { mUI->setupUi(this); diff --git a/gui/statsdialog.h b/gui/statsdialog.h index 1b7f41d0e..62c93fcab 100644 --- a/gui/statsdialog.h +++ b/gui/statsdialog.h @@ -73,7 +73,7 @@ private slots: void pdfExport(); private: Ui::StatsDialog *mUI; - const CheckStatistics *mStatistics; + const CheckStatistics* mStatistics{}; }; /// @} diff --git a/gui/test/projectfile/testprojectfile.cpp b/gui/test/projectfile/testprojectfile.cpp index 95cbe9404..cbd98dc86 100644 --- a/gui/test/projectfile/testprojectfile.cpp +++ b/gui/test/projectfile/testprojectfile.cpp @@ -39,9 +39,8 @@ const char Settings::SafeChecks::XmlClasses[] = "class-public"; const char Settings::SafeChecks::XmlExternalFunctions[] = "external-functions"; const char Settings::SafeChecks::XmlInternalFunctions[] = "internal-functions"; const char Settings::SafeChecks::XmlExternalVariables[] = "external-variables"; -Settings::Settings() : maxCtuDepth(10), maxTemplateRecursion(100) {} +Settings::Settings() : maxCtuDepth(10) {} cppcheck::Platform::Platform() {} -Library::Library() {} ImportProject::ImportProject() {} bool ImportProject::sourceFileExists(const std::string & /*file*/) { return true; diff --git a/gui/threadhandler.cpp b/gui/threadhandler.cpp index fddb33480..43faf2aea 100644 --- a/gui/threadhandler.cpp +++ b/gui/threadhandler.cpp @@ -36,11 +36,7 @@ #include ThreadHandler::ThreadHandler(QObject *parent) : - QObject(parent), - mScanDuration(0), - mRunningThreadCount(0), - mAnalyseWholeProgram(false) - + QObject(parent) { setThreadCount(1); } diff --git a/gui/threadhandler.h b/gui/threadhandler.h index 93d30893d..cdf2a6f02 100644 --- a/gui/threadhandler.h +++ b/gui/threadhandler.h @@ -230,7 +230,7 @@ protected: * @brief The previous scan duration in milliseconds. * */ - int mScanDuration; + int mScanDuration{}; /** * @brief Function to delete all threads @@ -254,9 +254,9 @@ protected: * @brief The amount of threads currently running * */ - int mRunningThreadCount; + int mRunningThreadCount{}; - bool mAnalyseWholeProgram; + bool mAnalyseWholeProgram{}; QStringList mAddonsAndTools; QList mSuppressions; diff --git a/gui/threadresult.cpp b/gui/threadresult.cpp index f32da9b1c..5e1aed89b 100644 --- a/gui/threadresult.cpp +++ b/gui/threadresult.cpp @@ -28,11 +28,6 @@ #include #include -ThreadResult::ThreadResult() : QObject(), ErrorLogger(), mMaxProgress(0), mProgress(0), mFilesChecked(0), mTotalFiles(0) -{ - //ctor -} - ThreadResult::~ThreadResult() { //dtor diff --git a/gui/threadresult.h b/gui/threadresult.h index 9a3c58953..f08bb9452 100644 --- a/gui/threadresult.h +++ b/gui/threadresult.h @@ -45,7 +45,7 @@ class ErrorItem; class ThreadResult : public QObject, public ErrorLogger { Q_OBJECT public: - ThreadResult(); + ThreadResult() = default; ~ThreadResult() override; /** @@ -142,25 +142,25 @@ protected: * @brief Max progress * */ - quint64 mMaxProgress; + quint64 mMaxProgress{}; /** * @brief Current progress * */ - quint64 mProgress; + quint64 mProgress{}; /** * @brief Current number of files checked * */ - unsigned long mFilesChecked; + unsigned long mFilesChecked{}; /** * @brief Total number of files * */ - unsigned long mTotalFiles; + unsigned long mTotalFiles{}; }; /// @} #endif // THREADRESULT_H diff --git a/gui/translationhandler.cpp b/gui/translationhandler.cpp index 0a0aefd07..6b14b6241 100644 --- a/gui/translationhandler.cpp +++ b/gui/translationhandler.cpp @@ -42,8 +42,7 @@ static UNUSED void unused() TranslationHandler::TranslationHandler(QObject *parent) : QObject(parent), - mCurrentLanguage("en"), - mTranslator(nullptr) + mCurrentLanguage("en") { // Add our available languages // Keep this list sorted diff --git a/gui/translationhandler.h b/gui/translationhandler.h index 66effc5ed..e9ff87220 100644 --- a/gui/translationhandler.h +++ b/gui/translationhandler.h @@ -135,7 +135,7 @@ private: * @brief Translator class instance. * */ - QTranslator *mTranslator; + QTranslator* mTranslator{}; }; /// @} diff --git a/lib/analyzer.h b/lib/analyzer.h index 51da0281f..3c65e0e68 100644 --- a/lib/analyzer.h +++ b/lib/analyzer.h @@ -32,7 +32,7 @@ class ValuePtr; struct Analyzer { struct Action { - Action() : mFlag(0) {} + Action() = default; template ), @@ -125,7 +125,7 @@ struct Analyzer { } private: - unsigned int mFlag; + unsigned int mFlag{}; }; enum class Terminate { None, Bail, Escape, Modified, Inconclusive, Conditional }; diff --git a/lib/check.cpp b/lib/check.cpp index f01d938a6..bc67e683d 100644 --- a/lib/check.cpp +++ b/lib/check.cpp @@ -35,7 +35,7 @@ //--------------------------------------------------------------------------- Check::Check(const std::string &aname) - : mTokenizer(nullptr), mSettings(nullptr), mErrorLogger(nullptr), mName(aname) + : mName(aname) { { const auto it = std::find_if(instances().begin(), instances().end(), [&](const Check *i) { diff --git a/lib/check.h b/lib/check.h index 2f29d9b1d..39e347815 100644 --- a/lib/check.h +++ b/lib/check.h @@ -130,9 +130,9 @@ public: static std::string getMessageId(const ValueFlow::Value &value, const char id[]); protected: - const Tokenizer * const mTokenizer; - const Settings * const mSettings; - ErrorLogger * const mErrorLogger; + const Tokenizer* const mTokenizer{}; + const Settings* const mSettings{}; + ErrorLogger* const mErrorLogger{}; /** report an error */ void reportError(const Token *tok, const Severity::SeverityType severity, const std::string &id, const std::string &msg) { diff --git a/lib/checkclass.h b/lib/checkclass.h index bd1ed8db0..ffb94d3a2 100644 --- a/lib/checkclass.h +++ b/lib/checkclass.h @@ -53,7 +53,7 @@ namespace tinyxml2 { class CPPCHECKLIB CheckClass : public Check { public: /** @brief This constructor is used when registering the CheckClass */ - CheckClass() : Check(myName()), mSymbolDatabase(nullptr) {} + CheckClass() : Check(myName()) {} /** @brief This constructor is used when running checks. */ CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger); @@ -195,7 +195,7 @@ public: static const std::set stl_containers_not_const; private: - const SymbolDatabase *mSymbolDatabase; + const SymbolDatabase* mSymbolDatabase{}; // Reporting errors.. void noConstructorError(const Token *tok, const std::string &classname, bool isStruct); @@ -330,16 +330,16 @@ private: // constructors helper function /** @brief Information about a member variable. Used when checking for uninitialized variables */ struct Usage { - explicit Usage(const Variable *var) : var(var), assign(false), init(false) {} + explicit Usage(const Variable *var) : var(var) {} /** Variable that this usage is for */ const Variable *var; /** @brief has this variable been assigned? */ - bool assign; + bool assign{}; /** @brief has this variable been initialized? */ - bool init; + bool init{}; }; static bool isBaseClassMutableMemberFunc(const Token *tok, const Scope *scope); diff --git a/lib/checkio.cpp b/lib/checkio.cpp index 2a0fdc4d4..dc14c0832 100644 --- a/lib/checkio.cpp +++ b/lib/checkio.cpp @@ -106,14 +106,14 @@ static OpenMode getMode(const std::string& str) struct Filepointer { OpenMode mode; - nonneg int mode_indent; - enum class Operation {NONE, UNIMPORTANT, READ, WRITE, POSITIONING, OPEN, CLOSE, UNKNOWN_OP} lastOperation; - nonneg int op_indent; + nonneg int mode_indent{}; + enum class Operation {NONE, UNIMPORTANT, READ, WRITE, POSITIONING, OPEN, CLOSE, UNKNOWN_OP} lastOperation = Operation::NONE; + nonneg int op_indent{}; enum class AppendMode { UNKNOWN_AM, APPEND, APPEND_EX }; - AppendMode append_mode; + AppendMode append_mode = AppendMode::UNKNOWN_AM; std::string filename; explicit Filepointer(OpenMode mode_ = OpenMode::UNKNOWN_OM) - : mode(mode_), mode_indent(0), lastOperation(Operation::NONE), op_indent(0), append_mode(AppendMode::UNKNOWN_AM) {} + : mode(mode_) {} }; namespace { @@ -1331,14 +1331,7 @@ void CheckIO::checkFormatString(const Token * const tok, /// @todo add non-string literals, and generic expressions CheckIO::ArgumentInfo::ArgumentInfo(const Token * arg, const Settings *settings, bool _isCPP) - : variableInfo(nullptr) - , typeToken(nullptr) - , functionInfo(nullptr) - , tempToken(nullptr) - , element(false) - , _template(false) - , address(false) - , isCPP(_isCPP) + : isCPP(_isCPP) { if (!arg) return; diff --git a/lib/checkio.h b/lib/checkio.h index 9e9b07a25..29c3344d5 100644 --- a/lib/checkio.h +++ b/lib/checkio.h @@ -86,14 +86,14 @@ private: bool isStdContainer(const Token *tok); bool isLibraryType(const Settings *settings) const; - const Variable *variableInfo; - const Token *typeToken; - const Function *functionInfo; - Token *tempToken; - bool element; - bool _template; - bool address; - bool isCPP; + const Variable* variableInfo{}; + const Token* typeToken{}; + const Function* functionInfo{}; + Token* tempToken{}; + bool element{}; + bool _template{}; + bool address{}; + bool isCPP{}; }; void checkFormatString(const Token * const tok, diff --git a/lib/checkuninitvar.h b/lib/checkuninitvar.h index 8c4ccbccb..fbb645e07 100644 --- a/lib/checkuninitvar.h +++ b/lib/checkuninitvar.h @@ -48,9 +48,9 @@ namespace tinyxml2 { struct VariableValue { - explicit VariableValue(MathLib::bigint val = 0) : value(val), notEqual(false) {} + explicit VariableValue(MathLib::bigint val = 0) : value(val) {} MathLib::bigint value; - bool notEqual; + bool notEqual{}; }; /// @addtogroup Checks diff --git a/lib/checkunusedfunctions.h b/lib/checkunusedfunctions.h index d635b817d..af008a17b 100644 --- a/lib/checkunusedfunctions.h +++ b/lib/checkunusedfunctions.h @@ -101,14 +101,11 @@ private: return "Check for functions that are never called\n"; } - class CPPCHECKLIB FunctionUsage { - public: - FunctionUsage() : lineNumber(0), usedSameFile(false), usedOtherFile(false) {} - + struct CPPCHECKLIB FunctionUsage { std::string filename; - unsigned int lineNumber; - bool usedSameFile; - bool usedOtherFile; + unsigned int lineNumber{}; + bool usedSameFile{}; + bool usedOtherFile{}; }; std::unordered_map mFunctions; diff --git a/lib/checkunusedvar.cpp b/lib/checkunusedvar.cpp index 9f0ea5dc3..68366756f 100644 --- a/lib/checkunusedvar.cpp +++ b/lib/checkunusedvar.cpp @@ -635,7 +635,7 @@ static bool isPartOfClassStructUnion(const Token* tok) if (tok->str() == "}" || tok->str() == ")") tok = tok->link(); else if (tok->str() == "(") - return (false); + return false; else if (tok->str() == "{") { return (tok->strAt(-1) == "struct" || tok->strAt(-2) == "struct" || tok->strAt(-1) == "class" || tok->strAt(-2) == "class" || tok->strAt(-1) == "union" || tok->strAt(-2) == "union"); } diff --git a/lib/clangimport.cpp b/lib/clangimport.cpp index 328d65275..7b91d6c4b 100644 --- a/lib/clangimport.cpp +++ b/lib/clangimport.cpp @@ -205,10 +205,10 @@ static std::vector splitString(const std::string &line) namespace clangimport { struct Data { struct Decl { - explicit Decl(Scope *scope) : def(nullptr), enumerator(nullptr), function(nullptr), scope(scope), var(nullptr) {} - Decl(Token *def, Variable *var) : def(def), enumerator(nullptr), function(nullptr), scope(nullptr), var(var) {} - Decl(Token *def, Function *function) : def(def), enumerator(nullptr), function(function), scope(nullptr), var(nullptr) {} - Decl(Token *def, Enumerator *enumerator) : def(def), enumerator(enumerator), function(nullptr), scope(nullptr), var(nullptr) {} + explicit Decl(Scope *scope) : scope(scope) {} + Decl(Token *def, Variable *var) : def(def), var(var) {} + Decl(Token *def, Function *function) : def(def), function(function) {} + Decl(Token *def, Enumerator *enumerator) : def(def), enumerator(enumerator) {} void ref(Token *tok) const { if (enumerator) tok->enumerator(enumerator); @@ -219,11 +219,11 @@ namespace clangimport { tok->varId(var->declarationId()); } } - Token *def; - Enumerator *enumerator; - Function *function; - Scope *scope; - Variable *var; + Token* def{}; + Enumerator* enumerator{}; + Function* function{}; + Scope* scope{}; + Variable* var{}; }; const Settings *mSettings = nullptr; diff --git a/lib/cppcheck.cpp b/lib/cppcheck.cpp index 9b7a72cad..074e5ce71 100644 --- a/lib/cppcheck.cpp +++ b/lib/cppcheck.cpp @@ -391,10 +391,7 @@ CppCheck::CppCheck(ErrorLogger &errorLogger, bool useGlobalSuppressions, std::function,std::string,std::string&)> executeCommand) : mErrorLogger(errorLogger) - , mExitCode(0) , mUseGlobalSuppressions(useGlobalSuppressions) - , mTooManyConfigs(false) - , mSimplify(true) , mExecuteCommand(std::move(executeCommand)) {} diff --git a/lib/cppcheck.h b/lib/cppcheck.h index d9b63f02f..925111ae7 100644 --- a/lib/cppcheck.h +++ b/lib/cppcheck.h @@ -217,15 +217,15 @@ private: /** @brief Current preprocessor configuration */ std::string mCurrentConfig; - unsigned int mExitCode; + unsigned int mExitCode{}; bool mUseGlobalSuppressions; /** Are there too many configs? */ - bool mTooManyConfigs; + bool mTooManyConfigs{}; /** Simplify code? true by default */ - bool mSimplify; + bool mSimplify = true; /** File info used for whole program analysis */ std::list mFileInfo; diff --git a/lib/ctu.cpp b/lib/ctu.cpp index ab3a7155d..d62f91bfb 100644 --- a/lib/ctu.cpp +++ b/lib/ctu.cpp @@ -158,7 +158,6 @@ std::string CTU::toString(const std::list &unsafeUsa CTU::FileInfo::CallBase::CallBase(const Tokenizer *tokenizer, const Token *callToken) : callId(getFunctionId(tokenizer, callToken->function())) - , callArgNr(0) , callFunctionName(callToken->next()->astOperand1()->expressionString()) , location(CTU::FileInfo::Location(tokenizer, callToken)) {} @@ -166,7 +165,6 @@ CTU::FileInfo::CallBase::CallBase(const Tokenizer *tokenizer, const Token *callT CTU::FileInfo::NestedCall::NestedCall(const Tokenizer *tokenizer, const Function *myFunction, const Token *callToken) : CallBase(tokenizer, callToken) , myId(getFunctionId(tokenizer, myFunction)) - , myArgNr(0) {} static std::string readAttrString(const tinyxml2::XMLElement *e, const char *attr, bool *error) diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 494dbd13b..fea0526eb 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -51,15 +51,15 @@ struct ForwardTraversal { enum class Progress { Continue, Break, Skip }; enum class Terminate { None, Bail, Inconclusive }; ForwardTraversal(const ValuePtr& analyzer, const Settings& settings) - : analyzer(analyzer), settings(settings), actions(Analyzer::Action::None), analyzeOnly(false), analyzeTerminate(false) + : analyzer(analyzer), settings(settings) {} ValuePtr analyzer; const Settings& settings; Analyzer::Action actions; - bool analyzeOnly; - bool analyzeTerminate; + bool analyzeOnly{}; + bool analyzeTerminate{}; Analyzer::Terminate terminate = Analyzer::Terminate::None; - std::vector loopEnds = {}; + std::vector loopEnds; Progress Break(Analyzer::Terminate t = Analyzer::Terminate::None) { if ((!analyzeOnly || analyzeTerminate) && t != Analyzer::Terminate::None) diff --git a/lib/fwdanalysis.h b/lib/fwdanalysis.h index 847d1464e..0e83c2251 100644 --- a/lib/fwdanalysis.h +++ b/lib/fwdanalysis.h @@ -37,7 +37,7 @@ class Library; */ class FwdAnalysis { public: - FwdAnalysis(bool cpp, const Library &library) : mCpp(cpp), mLibrary(library), mWhat(What::Reassign), mValueFlowKnown(true) {} + FwdAnalysis(bool cpp, const Library &library) : mCpp(cpp), mLibrary(library) {} bool hasOperand(const Token *tok, const Token *lhs) const; @@ -60,8 +60,8 @@ public: bool unusedValue(const Token *expr, const Token *startToken, const Token *endToken); struct KnownAndToken { - bool known; - const Token *token; + bool known{}; + const Token* token{}; }; /** Is there some possible alias for given expression */ @@ -74,9 +74,9 @@ private: /** Result of forward analysis */ struct Result { enum class Type { NONE, READ, WRITE, BREAK, RETURN, BAILOUT } type; - explicit Result(Type type) : type(type), token(nullptr) {} + explicit Result(Type type) : type(type) {} Result(Type type, const Token *token) : type(type), token(token) {} - const Token *token; + const Token* token{}; }; struct Result check(const Token *expr, const Token *startToken, const Token *endToken); @@ -87,9 +87,9 @@ private: const bool mCpp; const Library &mLibrary; - enum class What { Reassign, UnusedValue, ValueFlow } mWhat; + enum class What { Reassign, UnusedValue, ValueFlow } mWhat = What::Reassign; std::vector mValueFlow; - bool mValueFlowKnown; + bool mValueFlowKnown = true; }; #endif // fwdanalysisH diff --git a/lib/importproject.cpp b/lib/importproject.cpp index c59bf288a..76403ff40 100644 --- a/lib/importproject.cpp +++ b/lib/importproject.cpp @@ -502,7 +502,7 @@ bool ImportProject::importSln(std::istream &istr, const std::string &path, const namespace { struct ProjectConfiguration { - explicit ProjectConfiguration(const tinyxml2::XMLElement *cfg) : platform(Unknown) { + explicit ProjectConfiguration(const tinyxml2::XMLElement *cfg) { const char *a = cfg->Attribute("Include"); if (a) name = a; @@ -524,7 +524,7 @@ namespace { } std::string name; std::string configuration; - enum { Win32, x64, Unknown } platform; + enum { Win32, x64, Unknown } platform = Unknown; std::string platformStr; }; diff --git a/lib/importproject.h b/lib/importproject.h index 704722edc..1d7bb9ba7 100644 --- a/lib/importproject.h +++ b/lib/importproject.h @@ -63,7 +63,6 @@ public: /** File settings. Multiple configurations for a file is allowed. */ struct CPPCHECKLIB FileSettings { - FileSettings() : platformType(cppcheck::Platform::Type::Unspecified), msc(false), useMfc(false) {} std::string cfg; std::string filename; std::string defines; @@ -74,9 +73,9 @@ public: std::list includePaths; std::list systemIncludePaths; std::string standard; - cppcheck::Platform::Type platformType; - bool msc; - bool useMfc; + cppcheck::Platform::Type platformType = cppcheck::Platform::Type::Unspecified; + bool msc{}; + bool useMfc{}; void parseCommand(const std::string& command); void setDefines(std::string defs); diff --git a/lib/library.cpp b/lib/library.cpp index 3744f4552..4142dcd8a 100644 --- a/lib/library.cpp +++ b/lib/library.cpp @@ -64,9 +64,6 @@ static void gettokenlistfromvalid(const std::string& valid, TokenList& tokenList } } -Library::Library() : mAllocId(0) -{} - Library::Error Library::load(const char exename[], const char path[]) { if (std::strchr(path,',') != nullptr) { diff --git a/lib/library.h b/lib/library.h index 2e38a7332..300382d9f 100644 --- a/lib/library.h +++ b/lib/library.h @@ -58,7 +58,7 @@ class CPPCHECKLIB Library { friend class TestProcessExecutor; // For testing only public: - Library(); + Library() = default; enum class ErrorCode { OK, FILE_NOT_FOUND, BAD_XML, UNKNOWN_ELEMENT, MISSING_ATTRIBUTE, BAD_ATTRIBUTE_VALUE, UNSUPPORTED_FORMAT, DUPLICATE_PLATFORM_TYPE, PLATFORM_TYPE_REDEFINED }; @@ -210,18 +210,7 @@ public: class Container { public: - Container() - : type_templateArgNo(-1), - size_templateArgNo(-1), - arrayLike_indexOp(false), - stdStringLike(false), - stdAssociativeLike(false), - opLessAllowed(true), - hasInitializerListConstructor(false), - unstableErase(false), - unstableInsert(false), - view(false) - {} + Container() = default; enum class Action { RESIZE, @@ -259,17 +248,17 @@ public: }; std::string startPattern, startPattern2, endPattern, itEndPattern; std::map functions; - int type_templateArgNo; + int type_templateArgNo = -1; std::vector rangeItemRecordType; - int size_templateArgNo; - bool arrayLike_indexOp; - bool stdStringLike; - bool stdAssociativeLike; - bool opLessAllowed; - bool hasInitializerListConstructor; - bool unstableErase; - bool unstableInsert; - bool view; + int size_templateArgNo = -1; + bool arrayLike_indexOp{}; + bool stdStringLike{}; + bool stdAssociativeLike{}; + bool opLessAllowed = true; + bool hasInitializerListConstructor{}; + bool unstableErase{}; + bool unstableInsert{}; + bool view{}; Action getAction(const std::string& function) const { const std::map::const_iterator i = functions.find(function); @@ -298,47 +287,31 @@ public: const Container* detectIterator(const Token* typeStart) const; const Container* detectContainerOrIterator(const Token* typeStart, bool* isIterator = nullptr, bool withoutStd = false) const; - class ArgumentChecks { - public: - ArgumentChecks() : - notbool(false), - notnull(false), - notuninit(-1), - formatstr(false), - strz(false), - optional(false), - variadic(false), - iteratorInfo(), - direction(Direction::DIR_UNKNOWN) {} - - bool notbool; - bool notnull; - int notuninit; - bool formatstr; - bool strz; - bool optional; - bool variadic; + struct ArgumentChecks { + bool notbool{}; + bool notnull{}; + int notuninit = -1; + bool formatstr{}; + bool strz{}; + bool optional{}; + bool variadic{}; std::string valid; - class IteratorInfo { - public: - IteratorInfo() : container(0), it(false), first(false), last(false) {} - - int container; - bool it; - bool first; - bool last; + struct IteratorInfo { + int container{}; + bool it{}; + bool first{}; + bool last{}; }; IteratorInfo iteratorInfo; - class MinSize { - public: + struct MinSize { enum class Type { NONE, STRLEN, ARGVALUE, SIZEOF, MUL, VALUE }; - MinSize(Type t, int a) : type(t), arg(a), arg2(0), value(0) {} + MinSize(Type t, int a) : type(t), arg(a) {} Type type; int arg; - int arg2; - long long value; + int arg2 = 0; + long long value = 0; std::string baseType; }; std::vector minsizes; @@ -349,36 +322,23 @@ public: DIR_INOUT, ///< Input to called function, and output to caller. Data is passed by reference or address and is potentially modified. DIR_UNKNOWN ///< direction not known / specified }; - Direction direction; + Direction direction = Direction::DIR_UNKNOWN; }; struct Function { std::map argumentChecks; // argument nr => argument data - bool use; - bool leakignore; - bool isconst; - bool ispure; - UseRetValType useretval; - bool ignore; // ignore functions/macros from a library (gtk, qt etc) - bool formatstr; - bool formatstr_scan; - bool formatstr_secure; - Container::Action containerAction; - Container::Yield containerYield; + bool use{}; + bool leakignore{}; + bool isconst{}; + bool ispure{}; + UseRetValType useretval = UseRetValType::NONE; + bool ignore{}; // ignore functions/macros from a library (gtk, qt etc) + bool formatstr{}; + bool formatstr_scan{}; + bool formatstr_secure{}; + Container::Action containerAction = Container::Action::NO_ACTION; + Container::Yield containerYield = Container::Yield::NO_YIELD; std::string returnType; - Function() - : use(false), - leakignore(false), - isconst(false), - ispure(false), - useretval(UseRetValType::NONE), - ignore(false), - formatstr(false), - formatstr_scan(false), - formatstr_secure(false), - containerAction(Container::Action::NO_ACTION), - containerYield(Container::Yield::NO_YIELD) - {} }; const Function *getFunction(const Token *ftok) const; @@ -505,13 +465,6 @@ public: } struct PlatformType { - PlatformType() - : mSigned(false) - , mUnsigned(false) - , mLong(false) - , mPointer(false) - , mPtrPtr(false) - , mConstPtr(false) {} bool operator == (const PlatformType & type) const { return (mSigned == type.mSigned && mUnsigned == type.mUnsigned && @@ -525,12 +478,12 @@ public: return !(*this == type); } std::string mType; - bool mSigned; - bool mUnsigned; - bool mLong; - bool mPointer; - bool mPtrPtr; - bool mConstPtr; + bool mSigned{}; + bool mUnsigned{}; + bool mLong{}; + bool mPointer{}; + bool mPtrPtr{}; + bool mConstPtr{}; }; struct Platform { @@ -594,7 +547,7 @@ private: }; class CodeBlock { public: - CodeBlock() : mOffset(0) {} + CodeBlock() = default; void setStart(const char* s) { mStart = s; @@ -624,11 +577,11 @@ private: private: std::string mStart; std::string mEnd; - int mOffset; + int mOffset{}; std::set mBlocks; }; enum class FalseTrueMaybe { False, True, Maybe }; - int mAllocId; + int mAllocId{}; std::set mFiles; std::map mAlloc; // allocation functions std::map mDealloc; // deallocation functions diff --git a/lib/mathlib.cpp b/lib/mathlib.cpp index 501b6805b..7feef1f8c 100644 --- a/lib/mathlib.cpp +++ b/lib/mathlib.cpp @@ -37,8 +37,7 @@ const int MathLib::bigint_bits = 64; -MathLib::value::value(const std::string &s) : - mIntValue(0), mDoubleValue(0), mIsUnsigned(false) +MathLib::value::value(const std::string &s) { if (MathLib::isFloat(s)) { mType = MathLib::value::Type::FLOAT; diff --git a/lib/mathlib.h b/lib/mathlib.h index 709fb0e0b..9bab55a8d 100644 --- a/lib/mathlib.h +++ b/lib/mathlib.h @@ -37,10 +37,10 @@ public: /** @brief value class */ class value { private: - long long mIntValue; - double mDoubleValue; + long long mIntValue{}; + double mDoubleValue{}; enum class Type { INT, LONG, LONGLONG, FLOAT } mType; - bool mIsUnsigned; + bool mIsUnsigned{}; void promote(const value &v); diff --git a/lib/programmemory.cpp b/lib/programmemory.cpp index 6c4261eaf..05c42c461 100644 --- a/lib/programmemory.cpp +++ b/lib/programmemory.cpp @@ -429,7 +429,7 @@ static ProgramMemory getInitialProgramState(const Token* tok, return pm; } -ProgramMemoryState::ProgramMemoryState(const Settings* s) : state(), origins(), settings(s) {} +ProgramMemoryState::ProgramMemoryState(const Settings* s) : settings(s) {} void ProgramMemoryState::insert(const ProgramMemory &pm, const Token* origin) { diff --git a/lib/settings.cpp b/lib/settings.cpp index 3e40ef7c7..1efc55c90 100644 --- a/lib/settings.cpp +++ b/lib/settings.cpp @@ -36,44 +36,6 @@ const char Settings::SafeChecks::XmlInternalFunctions[] = "internal-functions"; const char Settings::SafeChecks::XmlExternalVariables[] = "external-variables"; Settings::Settings() - : checkAllConfigurations(true), - checkConfiguration(false), - checkHeaders(true), - checkLibrary(false), - checksMaxTime(0), - checkUnusedTemplates(true), - clang(false), - clangExecutable("clang"), - clangTidy(false), - clearIncludeCache(false), - daca(false), - debugnormal(false), - debugSimplified(false), - debugtemplate(false), - debugwarnings(false), - dump(false), - enforcedLang(Language::None), - exceptionHandling(false), - exitCode(0), - force(false), - inlineSuppressions(false), - jobs(1), - loadAverage(0), - maxConfigs(12), - maxCtuDepth(2), - maxTemplateRecursion(100), - performanceValueFlowMaxTime(-1), - preprocessOnly(false), - quiet(false), - relativePaths(false), - reportProgress(false), - showtime(SHOWTIME_MODES::SHOWTIME_NONE), - templateMaxTime(0), - typedefMaxTime(0), - valueFlowMaxIterations(4), - verbose(false), - xml(false), - xml_version(2) { severity.setEnabled(Severity::error, true); certainty.setEnabled(Certainty::normal, true); diff --git a/lib/settings.h b/lib/settings.h index c77ad2392..38c7111fb 100644 --- a/lib/settings.h +++ b/lib/settings.h @@ -114,39 +114,39 @@ public: std::string buildDir; /** @brief check all configurations (false if -D or --max-configs is used */ - bool checkAllConfigurations; + bool checkAllConfigurations = true; /** Is the 'configuration checking' wanted? */ - bool checkConfiguration; + bool checkConfiguration{}; /** * Check code in the headers, this is on by default but can * be turned off to save CPU */ - bool checkHeaders; + bool checkHeaders = true; /** Check for incomplete info in library files? */ - bool checkLibrary; + bool checkLibrary{}; /** @brief The maximum time in seconds for the checks of a single file */ - int checksMaxTime; + int checksMaxTime{}; /** @brief check unknown function return values */ std::set checkUnknownFunctionReturn; /** Check unused/uninstantiated templates */ - bool checkUnusedTemplates; + bool checkUnusedTemplates = true; /** Use Clang */ - bool clang; + bool clang{}; /** Custom Clang executable */ - std::string clangExecutable; + std::string clangExecutable = "clang"; /** Use clang-tidy */ - bool clangTidy; + bool clangTidy{}; /** Internal: Clear the simplecpp non-existing include cache */ - bool clearIncludeCache; + bool clearIncludeCache{}; /** @brief include paths excluded from checking the configuration */ std::set configExcludePaths; @@ -158,22 +158,22 @@ public: std::string cppcheckCfgAbout; /** @brief Are we running from DACA script? */ - bool daca; + bool daca{}; /** @brief Is --debug-normal given? */ - bool debugnormal; + bool debugnormal{}; /** @brief Is --debug-simplified given? */ - bool debugSimplified; + bool debugSimplified{}; /** @brief Is --debug-template given? */ - bool debugtemplate; + bool debugtemplate{}; /** @brief Is --debug-warnings given? */ - bool debugwarnings; + bool debugwarnings{}; /** @brief Is --dump given? */ - bool dump; + bool dump{}; std::string dumpFile; enum Language { @@ -181,34 +181,34 @@ public: }; /** @brief Name of the language that is enforced. Empty per default. */ - Language enforcedLang; + Language enforcedLang{}; /** @brief Is --exception-handling given */ - bool exceptionHandling; + bool exceptionHandling{}; // argv[0] std::string exename; /** @brief If errors are found, this value is returned from main(). Default value is 0. */ - int exitCode; + int exitCode{}; /** @brief List of --file-filter for analyzing special files */ std::vector fileFilters; /** @brief Force checking the files with "too many" configurations (--force). */ - bool force; + bool force{}; /** @brief List of include paths, e.g. "my/includes/" which should be used for finding include files inside source files. (-I) */ std::list includePaths; /** @brief Is --inline-suppr given? */ - bool inlineSuppressions; + bool inlineSuppressions{}; /** @brief How many processes/threads should do checking at the same time. Default is 1. (-j N) */ - unsigned int jobs; + unsigned int jobs = 1; /** @brief --library= */ std::list libraries; @@ -217,17 +217,17 @@ public: Library library; /** @brief Load average value */ - int loadAverage; + int loadAverage{}; /** @brief Maximum number of configurations to check before bailing. Default is 12. (--max-configs=N) */ - int maxConfigs; + int maxConfigs = 12; /** @brief --max-ctu-depth */ - int maxCtuDepth; + int maxCtuDepth = 2; /** @brief max template recursion */ - int maxTemplateRecursion; + int maxTemplateRecursion = 100; /** @brief suppress exitcode */ Suppressions nofail; @@ -241,7 +241,7 @@ public: cppcheck::Platform platform; /** @brief Experimental: --performance-valueflow-max-time=T */ - int performanceValueFlowMaxTime; + int performanceValueFlowMaxTime = -1; /** @brief --performance-valueflow-max-if-count=C */ int performanceValueFlowMaxIfCount; @@ -256,33 +256,26 @@ public: std::string premiumArgs; /** @brief Using -E for debugging purposes */ - bool preprocessOnly; + bool preprocessOnly{}; ImportProject project; /** @brief Is --quiet given? */ - bool quiet; + bool quiet{}; /** @brief Use relative paths in output. */ - bool relativePaths; + bool relativePaths{}; /** @brief --report-progress */ - bool reportProgress; + bool reportProgress{}; /** Rule */ - class CPPCHECKLIB Rule { - public: - Rule() - : tokenlist("normal") // use normal tokenlist - , id("rule") // default id - , severity(Severity::style) { // default severity - } - - std::string tokenlist; + struct CPPCHECKLIB Rule { + std::string tokenlist = "normal"; // use normal tokenlist std::string pattern; - std::string id; + std::string id = "rule"; // default id std::string summary; - Severity::SeverityType severity; + Severity::SeverityType severity = Severity::style; // default severity }; #ifdef HAVE_RULES @@ -293,9 +286,7 @@ public: #endif /** Do not only check how interface is used. Also check that interface is safe. */ - class CPPCHECKLIB SafeChecks { - public: - SafeChecks() : classes(false), externalFunctions(false), internalFunctions(false), externalVariables(false) {} + struct CPPCHECKLIB SafeChecks { static const char XmlRootName[]; static const char XmlClasses[]; @@ -313,26 +304,26 @@ public: * - public functions can be called in any order * - public variables can have any value */ - bool classes; + bool classes{}; /** * External functions * - external functions can be called in any order * - function parameters can have any values */ - bool externalFunctions; + bool externalFunctions{}; /** * Experimental: assume that internal functions can be used in any way * This is only available in the GUI. */ - bool internalFunctions; + bool internalFunctions{}; /** * Global variables that can be modified outside the TU. * - Such variable can have "any" value */ - bool externalVariables; + bool externalVariables{}; }; SafeChecks safeChecks; @@ -342,7 +333,7 @@ public: SimpleEnableGroup checks; /** @brief show timing information (--showtime=file|summary|top5) */ - SHOWTIME_MODES showtime; + SHOWTIME_MODES showtime{}; /** Struct contains standards settings */ Standards standards; @@ -356,10 +347,10 @@ public: std::string templateLocation; /** @brief The maximum time in seconds for the template instantiation */ - std::size_t templateMaxTime; + std::size_t templateMaxTime{}; /** @brief The maximum time in seconds for the typedef simplification */ - std::size_t typedefMaxTime; + std::size_t typedefMaxTime{}; /** @brief defines given by the user */ std::string userDefines; @@ -371,16 +362,16 @@ public: std::list userIncludes; /** @brief the maximum iterations of valueflow (--valueflow-max-iterations=T) */ - std::size_t valueFlowMaxIterations; + std::size_t valueFlowMaxIterations = 4; /** @brief Is --verbose given? */ - bool verbose; + bool verbose{}; /** @brief write XML results (--xml) */ - bool xml; + bool xml{}; /** @brief XML version (--xml-version=..) */ - int xml_version; + int xml_version = 2; /** * @brief return true if a included file is to be excluded in Preprocessor::getConfigs diff --git a/lib/standards.h b/lib/standards.h index e92656287..ee56d8881 100644 --- a/lib/standards.h +++ b/lib/standards.h @@ -35,17 +35,14 @@ */ struct Standards { /** C code standard */ - enum cstd_t { C89, C99, C11, CLatest=C11 } c; + enum cstd_t { C89, C99, C11, CLatest = C11 } c = CLatest; /** C++ code standard */ - enum cppstd_t { CPP03, CPP11, CPP14, CPP17, CPP20, CPP23, CPPLatest=CPP23 } cpp; + enum cppstd_t { CPP03, CPP11, CPP14, CPP17, CPP20, CPP23, CPPLatest = CPP23 } cpp = CPPLatest; /** --std value given on command line */ std::string stdValue; - /** This constructor clear all the variables **/ - Standards() : c(CLatest), cpp(CPPLatest) {} - bool setC(const std::string& str) { stdValue = str; if (str == "c89" || str == "C89") { diff --git a/lib/suppressions.h b/lib/suppressions.h index 2f0b339ed..cc64ee51c 100644 --- a/lib/suppressions.h +++ b/lib/suppressions.h @@ -55,8 +55,8 @@ public: }; struct CPPCHECKLIB Suppression { - Suppression() : lineNumber(NO_LINE), hash(0), thisAndNextLine(false), matched(false), checked(false) {} - Suppression(std::string id, std::string file, int line=NO_LINE) : errorId(std::move(id)), fileName(std::move(file)), lineNumber(line), hash(0), thisAndNextLine(false), matched(false), checked(false) {} + Suppression() = default; + Suppression(std::string id, std::string file, int line=NO_LINE) : errorId(std::move(id)), fileName(std::move(file)), lineNumber(line) {} bool operator<(const Suppression &other) const { if (errorId != other.errorId) @@ -103,12 +103,12 @@ public: std::string errorId; std::string fileName; - int lineNumber; + int lineNumber = NO_LINE; std::string symbolName; - std::size_t hash; - bool thisAndNextLine; // Special case for backwards compatibility: { // cppcheck-suppress something - bool matched; - bool checked; // for inline suppressions, checked or not + std::size_t hash{}; + bool thisAndNextLine{}; // Special case for backwards compatibility: { // cppcheck-suppress something + bool matched{}; + bool checked{}; // for inline suppressions, checked or not enum { NO_LINE = -1 }; }; diff --git a/lib/symboldatabase.cpp b/lib/symboldatabase.cpp index 97f644f4c..005d0dc22 100644 --- a/lib/symboldatabase.cpp +++ b/lib/symboldatabase.cpp @@ -2086,8 +2086,7 @@ Variable::Variable(const Token *name_, const std::string &clangType, const Token mAccess(access_), mFlags(0), mType(type_), - mScope(scope_), - mValueType(nullptr) + mScope(scope_) { if (!mTypeStartToken && mTypeEndToken) { mTypeStartToken = mTypeEndToken; @@ -2135,14 +2134,12 @@ Variable::Variable(const Token *name_, const std::string &clangType, const Token } Variable::Variable(const Variable &var, const Scope *scope) - : mValueType(nullptr) { *this = var; mScope = scope; } Variable::Variable(const Variable &var) - : mValueType(nullptr) { *this = var; } @@ -2401,20 +2398,7 @@ Function::Function(const Tokenizer *mTokenizer, const Token *tokArgDef) : tokenDef(tokDef), argDef(tokArgDef), - token(nullptr), - arg(nullptr), - retDef(nullptr), - retType(nullptr), - functionScope(nullptr), - nestedIn(scope), - initArgCount(0), - type(eFunction), - noexceptArg(nullptr), - throwArg(nullptr), - templateDef(nullptr), - functionPointerUsage(nullptr), - access(AccessControl::Public), - mFlags(0) + nestedIn(scope) { // operator function if (::isOperator(tokenDef)) { @@ -2519,22 +2503,7 @@ Function::Function(const Tokenizer *mTokenizer, } Function::Function(const Token *tokenDef, const std::string &clangType) - : tokenDef(tokenDef), - argDef(nullptr), - token(nullptr), - arg(nullptr), - retDef(nullptr), - retType(nullptr), - functionScope(nullptr), - nestedIn(nullptr), - initArgCount(0), - type(eFunction), - noexceptArg(nullptr), - throwArg(nullptr), - templateDef(nullptr), - functionPointerUsage(nullptr), - access(AccessControl::Public), - mFlags(0) + : tokenDef(tokenDef) { // operator function if (::isOperator(tokenDef)) { @@ -4461,14 +4430,7 @@ Scope::Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope * check(check_), classDef(classDef_), nestedIn(nestedIn_), - numConstructors(0), - numCopyOrMoveConstructors(0), - type(type_), - definedType(nullptr), - functionOf(nullptr), - function(nullptr), - enumType(nullptr), - enumClass(false) + type(type_) { setBodyStartEnd(start_); } @@ -4476,16 +4438,7 @@ Scope::Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope * Scope::Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope *nestedIn_) : check(check_), classDef(classDef_), - bodyStart(nullptr), - bodyEnd(nullptr), - nestedIn(nestedIn_), - numConstructors(0), - numCopyOrMoveConstructors(0), - definedType(nullptr), - functionOf(nullptr), - function(nullptr), - enumType(nullptr), - enumClass(false) + nestedIn(nestedIn_) { const Token *nameTok = classDef; if (!classDef) { diff --git a/lib/symboldatabase.h b/lib/symboldatabase.h index aa7d644a6..d7c50ee7a 100644 --- a/lib/symboldatabase.h +++ b/lib/symboldatabase.h @@ -60,11 +60,9 @@ enum class AccessControl { Public, Protected, Private, Global, Namespace, Argume * @brief Array dimension information. */ struct Dimension { - Dimension() : tok(nullptr), num(0), known(true) {} - - const Token *tok; ///< size token - MathLib::bigint num; ///< (assumed) dimension length when size is a number, 0 if not known - bool known; ///< Known size + const Token* tok{}; ///< size token + MathLib::bigint num{}; ///< (assumed) dimension length when size is a number, 0 if not known + bool known = true; ///< Known size }; /** @brief Information about a class type. */ @@ -75,18 +73,14 @@ public: const Scope* enclosingScope; enum class NeedInitialization { Unknown, True, False - } needInitialization; - - class BaseInfo { - public: - BaseInfo() : - type(nullptr), nameTok(nullptr), access(AccessControl::Public), isVirtual(false) {} + } needInitialization = NeedInitialization::Unknown; + struct BaseInfo { std::string name; - const Type* type; - const Token* nameTok; - AccessControl access; // public/protected/private - bool isVirtual; + const Type* type{}; + const Token* nameTok{}; + AccessControl access{}; // public/protected/private + bool isVirtual{}; // allow ordering within containers bool operator<(const BaseInfo& rhs) const { return this->type < rhs.type; @@ -94,29 +88,22 @@ public: }; struct FriendInfo { - FriendInfo() : - nameStart(nullptr), nameEnd(nullptr), type(nullptr) {} - - const Token* nameStart; - const Token* nameEnd; - const Type* type; + const Token* nameStart{}; + const Token* nameEnd{}; + const Type* type{}; }; std::vector derivedFrom; std::vector friendList; - const Token * typeStart; - const Token * typeEnd; - MathLib::bigint sizeOf; + const Token* typeStart{}; + const Token* typeEnd{}; + MathLib::bigint sizeOf{}; explicit Type(const Token* classDef_ = nullptr, const Scope* classScope_ = nullptr, const Scope* enclosingScope_ = nullptr) : classDef(classDef_), classScope(classScope_), - enclosingScope(enclosingScope_), - needInitialization(NeedInitialization::Unknown), - typeStart(nullptr), - typeEnd(nullptr), - sizeOf(0) { + enclosingScope(enclosingScope_) { if (classDef_ && classDef_->str() == "enum") needInitialization = NeedInitialization::True; else if (classDef_ && classDef_->str() == "using") { @@ -167,15 +154,14 @@ public: bool isDerivedFrom(const std::string & ancestor) const; }; -class CPPCHECKLIB Enumerator { -public: - explicit Enumerator(const Scope * scope_) : scope(scope_), name(nullptr), value(0), start(nullptr), end(nullptr), value_known(false) {} +struct CPPCHECKLIB Enumerator { + explicit Enumerator(const Scope * scope_) : scope(scope_) {} const Scope * scope; - const Token * name; - MathLib::bigint value; - const Token * start; - const Token * end; - bool value_known; + const Token* name{}; + MathLib::bigint value{}; + const Token* start{}; + const Token* end{}; + bool value_known{}; }; /** @brief Information about a member variable. */ @@ -238,8 +224,7 @@ public: mAccess(access_), mFlags(0), mType(type_), - mScope(scope_), - mValueType(nullptr) { + mScope(scope_) { evaluate(settings); } @@ -699,7 +684,7 @@ private: /** @brief pointer to scope this variable is in */ const Scope *mScope; - const ValueType *mValueType; + const ValueType* mValueType{}; /** @brief array dimensions */ std::vector mDimensions; @@ -914,22 +899,22 @@ public: } bool isSafe(const Settings *settings) const; - const Token *tokenDef; ///< function name token in class definition - const Token *argDef; ///< function argument start '(' in class definition - const Token *token; ///< function name token in implementation - const Token *arg; ///< function argument start '(' - const Token *retDef; ///< function return type token - const ::Type *retType; ///< function return type - const Scope *functionScope; ///< scope of function body - const Scope* nestedIn; ///< Scope the function is declared in + const Token* tokenDef{}; ///< function name token in class definition + const Token* argDef{}; ///< function argument start '(' in class definition + const Token* token{}; ///< function name token in implementation + const Token* arg{}; ///< function argument start '(' + const Token* retDef{}; ///< function return type token + const ::Type* retType{}; ///< function return type + const Scope* functionScope{}; ///< scope of function body + const Scope* nestedIn{}; ///< Scope the function is declared in std::vector argumentList; ///< argument list - nonneg int initArgCount; ///< number of args with default values - Type type; ///< constructor, destructor, ... - const Token *noexceptArg; ///< noexcept token - const Token *throwArg; ///< throw token - const Token *templateDef; ///< points to 'template <' before function - const Token *functionPointerUsage; ///< function pointer usage - AccessControl access; ///< public/protected/private + nonneg int initArgCount{}; ///< number of args with default values + Type type = eFunction; ///< constructor, destructor, ... + const Token* noexceptArg{}; ///< noexcept token + const Token* throwArg{}; ///< throw token + const Token* templateDef{}; ///< points to 'template <' before function + const Token* functionPointerUsage{}; ///< function pointer usage + AccessControl access{}; ///< public/protected/private bool argsMatch(const Scope *scope, const Token *first, const Token *second, const std::string &path, nonneg int path_length) const; @@ -959,7 +944,7 @@ private: /** Recursively determine if this function overrides a virtual function in a base class */ const Function * getOverriddenFunctionRecursive(const ::Type* baseType, bool *foundAllBaseClasses) const; - unsigned int mFlags; + unsigned int mFlags{}; void isInline(bool state) { setFlag(fIsInline, state); @@ -1039,31 +1024,31 @@ public: Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope *nestedIn_); Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope *nestedIn_, ScopeType type_, const Token *start_); - const SymbolDatabase *check; + const SymbolDatabase* check{}; std::string className; - const Token *classDef; ///< class/struct/union/namespace token - const Token *bodyStart; ///< '{' token - const Token *bodyEnd; ///< '}' token + const Token* classDef{}; ///< class/struct/union/namespace token + const Token* bodyStart{}; ///< '{' token + const Token* bodyEnd{}; ///< '}' token std::list functionList; std::multimap functionMap; std::list varlist; - const Scope *nestedIn; + const Scope* nestedIn{}; std::vector nestedList; - nonneg int numConstructors; - nonneg int numCopyOrMoveConstructors; + nonneg int numConstructors{}; + nonneg int numCopyOrMoveConstructors{}; std::vector usingList; - ScopeType type; - Type* definedType; + ScopeType type{}; + Type* definedType{}; std::map definedTypesMap; std::vector bodyStartList; // function specific fields - const Scope *functionOf; ///< scope this function belongs to - Function *function; ///< function info for this function + const Scope* functionOf{}; ///< scope this function belongs to + Function* function{}; ///< function info for this function // enum specific fields - const Token * enumType; - bool enumClass; + const Token* enumType{}; + bool enumClass{}; std::vector enumeratorList; @@ -1224,7 +1209,7 @@ enum class Reference { /** Value type */ class CPPCHECKLIB ValueType { public: - enum Sign { UNKNOWN_SIGN, SIGNED, UNSIGNED } sign; + enum Sign { UNKNOWN_SIGN, SIGNED, UNSIGNED } sign = UNKNOWN_SIGN; enum Type { UNKNOWN_TYPE, POD, @@ -1245,80 +1230,42 @@ public: FLOAT, DOUBLE, LONGDOUBLE - } type; - nonneg int bits; ///< bitfield bitcount - nonneg int pointer; ///< 0=>not pointer, 1=>*, 2=>**, 3=>***, etc - nonneg int constness; ///< bit 0=data, bit 1=*, bit 2=** + } type = UNKNOWN_TYPE; + nonneg int bits{}; ///< bitfield bitcount + nonneg int pointer{}; ///< 0=>not pointer, 1=>*, 2=>**, 3=>***, etc + nonneg int constness{}; ///< bit 0=data, bit 1=*, bit 2=** Reference reference = Reference::None; ///< Is the outermost indirection of this type a reference or rvalue ///< reference or not? pointer=2, Reference=LValue would be a T**& - const Scope* typeScope; ///< if the type definition is seen this point out the type scope - const ::Type* smartPointerType; ///< Smart pointer type - const Token* smartPointerTypeToken; ///< Smart pointer type token - const Library::SmartPointer* smartPointer; ///< Smart pointer - const Library::Container* container; ///< If the type is a container defined in a cfg file, this is the used + const Scope* typeScope{}; ///< if the type definition is seen this point out the type scope + const ::Type* smartPointerType{}; ///< Smart pointer type + const Token* smartPointerTypeToken{}; ///< Smart pointer type token + const Library::SmartPointer* smartPointer{}; ///< Smart pointer + const Library::Container* container{}; ///< If the type is a container defined in a cfg file, this is the used ///< container - const Token* containerTypeToken; ///< The container type token. the template argument token that defines the + const Token* containerTypeToken{}; ///< The container type token. the template argument token that defines the ///< container element type. std::string originalTypeName; ///< original type name as written in the source code. eg. this might be "uint8_t" ///< when type is CHAR. ErrorPath debugPath; ///< debug path to the type - ValueType() - : sign(UNKNOWN_SIGN), - type(UNKNOWN_TYPE), - bits(0), - pointer(0U), - constness(0U), - typeScope(nullptr), - smartPointerType(nullptr), - smartPointerTypeToken(nullptr), - smartPointer(nullptr), - container(nullptr), - containerTypeToken(nullptr), - debugPath() - {} + ValueType() = default; ValueType(enum Sign s, enum Type t, nonneg int p) : sign(s), type(t), - bits(0), - pointer(p), - constness(0U), - typeScope(nullptr), - smartPointerType(nullptr), - smartPointerTypeToken(nullptr), - smartPointer(nullptr), - container(nullptr), - containerTypeToken(nullptr), - debugPath() + pointer(p) {} ValueType(enum Sign s, enum Type t, nonneg int p, nonneg int c) : sign(s), type(t), - bits(0), pointer(p), - constness(c), - typeScope(nullptr), - smartPointerType(nullptr), - smartPointerTypeToken(nullptr), - smartPointer(nullptr), - container(nullptr), - containerTypeToken(nullptr), - debugPath() + constness(c) {} ValueType(enum Sign s, enum Type t, nonneg int p, nonneg int c, std::string otn) : sign(s), type(t), - bits(0), pointer(p), constness(c), - typeScope(nullptr), - smartPointerType(nullptr), - smartPointerTypeToken(nullptr), - smartPointer(nullptr), - container(nullptr), - containerTypeToken(nullptr), - originalTypeName(std::move(otn)), - debugPath() + originalTypeName(std::move(otn)) {} static ValueType parseDecl(const Token *type, const Settings &settings, bool isCpp); diff --git a/lib/templatesimplifier.cpp b/lib/templatesimplifier.cpp index 3ff539ae0..e551790a4 100644 --- a/lib/templatesimplifier.cpp +++ b/lib/templatesimplifier.cpp @@ -281,7 +281,7 @@ bool TemplateSimplifier::TokenAndName::isAliasToken(const Token *tok) const TemplateSimplifier::TemplateSimplifier(Tokenizer &tokenizer) : mTokenizer(tokenizer), mTokenList(mTokenizer.list), mSettings(*mTokenizer.mSettings), - mErrorLogger(mTokenizer.mErrorLogger), mChanged(false) + mErrorLogger(mTokenizer.mErrorLogger) {} TemplateSimplifier::~TemplateSimplifier() diff --git a/lib/templatesimplifier.h b/lib/templatesimplifier.h index 23dad621b..763962ea2 100644 --- a/lib/templatesimplifier.h +++ b/lib/templatesimplifier.h @@ -500,7 +500,7 @@ private: TokenList &mTokenList; const Settings &mSettings; ErrorLogger *mErrorLogger; - bool mChanged; + bool mChanged{}; std::list mTemplateDeclarations; std::list mTemplateForwardDeclarations; diff --git a/lib/timer.cpp b/lib/timer.cpp index c5d3dfd12..4e04b5819 100644 --- a/lib/timer.cpp +++ b/lib/timer.cpp @@ -101,9 +101,6 @@ Timer::Timer(std::string str, SHOWTIME_MODES showtimeMode, TimerResultsIntf* tim Timer::Timer(bool fileTotal, std::string filename) : mStr(std::move(filename)) - , mTimerResults(nullptr) - , mStart(std::clock()) - , mShowTimeMode(SHOWTIME_MODES::SHOWTIME_FILE_TOTAL) , mStopped(!fileTotal) {} diff --git a/lib/timer.h b/lib/timer.h index 4bd8884c2..1fe246f41 100644 --- a/lib/timer.h +++ b/lib/timer.h @@ -43,12 +43,8 @@ public: }; struct TimerResultsData { - std::clock_t mClocks; - long mNumberOfResults; - - TimerResultsData() - : mClocks(0) - , mNumberOfResults(0) {} + std::clock_t mClocks{}; + long mNumberOfResults{}; double seconds() const { const double ret = (double)((unsigned long)mClocks) / (double)CLOCKS_PER_SEC; @@ -81,10 +77,10 @@ public: private: const std::string mStr; - TimerResultsIntf* mTimerResults; - std::clock_t mStart; - const SHOWTIME_MODES mShowTimeMode; - bool mStopped; + TimerResultsIntf* mTimerResults{}; + std::clock_t mStart = std::clock(); + const SHOWTIME_MODES mShowTimeMode = SHOWTIME_MODES::SHOWTIME_FILE_TOTAL; + bool mStopped{}; }; //--------------------------------------------------------------------------- #endif // timerH diff --git a/lib/token.cpp b/lib/token.cpp index 390490e86..0e9184626 100644 --- a/lib/token.cpp +++ b/lib/token.cpp @@ -56,12 +56,7 @@ namespace { const std::list TokenImpl::mEmptyValueList; Token::Token(TokensFrontBack *tokensFrontBack) : - mTokensFrontBack(tokensFrontBack), - mNext(nullptr), - mPrevious(nullptr), - mLink(nullptr), - mTokType(eNone), - mFlags(0) + mTokensFrontBack(tokensFrontBack) { mImpl = new TokenImpl(); } diff --git a/lib/token.h b/lib/token.h index 66016f33b..d04d365d4 100644 --- a/lib/token.h +++ b/lib/token.h @@ -39,7 +39,7 @@ #include #include -class Enumerator; +struct Enumerator; class Function; class Scope; class Settings; @@ -54,48 +54,48 @@ class Token; * @brief This struct stores pointers to the front and back tokens of the list this token is in. */ struct TokensFrontBack { - Token *front; - Token *back; - const TokenList* list; + Token *front{}; + Token* back{}; + const TokenList* list{}; }; struct ScopeInfo2 { ScopeInfo2(std::string name_, const Token *bodyEnd_, std::set usingNamespaces_ = std::set()) : name(std::move(name_)), bodyEnd(bodyEnd_), usingNamespaces(std::move(usingNamespaces_)) {} std::string name; - const Token * const bodyEnd; + const Token* const bodyEnd{}; std::set usingNamespaces; }; enum class TokenDebug { None, ValueFlow, ValueType }; struct TokenImpl { - nonneg int mVarId; - nonneg int mFileIndex; - nonneg int mLineNumber; - nonneg int mColumn; - nonneg int mExprId; + nonneg int mVarId{}; + nonneg int mFileIndex{}; + nonneg int mLineNumber{}; + nonneg int mColumn{}; + nonneg int mExprId{}; /** * A value from 0-100 that provides a rough idea about where in the token * list this token is located. */ - nonneg int mProgressValue; + nonneg int mProgressValue{}; /** * Token index. Position in token list */ - nonneg int mIndex; + nonneg int mIndex{}; /** Bitfield bit count. */ - unsigned char mBits; + unsigned char mBits{}; // AST.. - Token *mAstOperand1; - Token *mAstOperand2; - Token *mAstParent; + Token* mAstOperand1{}; + Token* mAstOperand2{}; + Token* mAstParent{}; // symbol database information - const Scope *mScope; + const Scope* mScope{}; union { const Function *mFunction; const Variable *mVariable; @@ -104,60 +104,38 @@ struct TokenImpl { }; // original name like size_t - std::string* mOriginalName; + std::string* mOriginalName{}; // ValueType - ValueType *mValueType; + ValueType* mValueType{}; // ValueFlow - std::list* mValues; + std::list* mValues{}; static const std::list mEmptyValueList; // Pointer to a template in the template simplifier - std::set* mTemplateSimplifierPointers; + std::set* mTemplateSimplifierPointers{}; // Pointer to the object representing this token's scope std::shared_ptr mScopeInfo; // __cppcheck_in_range__ struct CppcheckAttributes { - enum Type {LOW,HIGH} type; - MathLib::bigint value; - struct CppcheckAttributes *next; + enum Type { LOW, HIGH } type = LOW; + MathLib::bigint value{}; + CppcheckAttributes* next{}; }; - struct CppcheckAttributes *mCppcheckAttributes; + CppcheckAttributes* mCppcheckAttributes{}; // For memoization, to speed up parsing of huge arrays #8897 - enum class Cpp11init {UNKNOWN, CPP11INIT, NOINIT} mCpp11init; + enum class Cpp11init { UNKNOWN, CPP11INIT, NOINIT } mCpp11init = Cpp11init::UNKNOWN; - TokenDebug mDebug; + TokenDebug mDebug{}; void setCppcheckAttribute(CppcheckAttributes::Type type, MathLib::bigint value); bool getCppcheckAttribute(CppcheckAttributes::Type type, MathLib::bigint &value) const; - TokenImpl() - : mVarId(0), - mFileIndex(0), - mLineNumber(0), - mColumn(0), - mExprId(0), - mProgressValue(0), - mIndex(0), - mBits(0), - mAstOperand1(nullptr), - mAstOperand2(nullptr), - mAstParent(nullptr), - mScope(nullptr), - mFunction(nullptr), // Initialize whole union - mOriginalName(nullptr), - mValueType(nullptr), - mValues(nullptr), - mTemplateSimplifierPointers(nullptr), - mScopeInfo(nullptr), - mCppcheckAttributes(nullptr), - mCpp11init(Cpp11init::UNKNOWN), - mDebug(TokenDebug::None) - {} + TokenImpl() : mFunction(nullptr) {} ~TokenImpl(); }; @@ -177,7 +155,7 @@ struct TokenImpl { */ class CPPCHECKLIB Token { private: - TokensFrontBack* mTokensFrontBack; + TokensFrontBack* mTokensFrontBack{}; public: Token(const Token &) = delete; @@ -1301,9 +1279,9 @@ private: std::string mStr; - Token *mNext; - Token *mPrevious; - Token *mLink; + Token* mNext{}; + Token* mPrevious{}; + Token* mLink{}; enum : uint64_t { fIsUnsigned = (1ULL << 0), @@ -1355,11 +1333,11 @@ private: efIsUnique = efMaxSize - 2, }; - Token::Type mTokType; + Token::Type mTokType = eNone; - uint64_t mFlags; + uint64_t mFlags{}; - TokenImpl *mImpl; + TokenImpl* mImpl{}; /** * Get specified flag state. diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index deb580111..656db082f 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -64,15 +64,14 @@ namespace { // local struct used in setVarId // in order to store information about the scope struct VarIdScopeInfo { - VarIdScopeInfo() - : isExecutable(false), isStructInit(false), isEnum(false), startVarid(0) {} + VarIdScopeInfo() = default; VarIdScopeInfo(bool isExecutable, bool isStructInit, bool isEnum, nonneg int startVarid) : isExecutable(isExecutable), isStructInit(isStructInit), isEnum(isEnum), startVarid(startVarid) {} - const bool isExecutable; - const bool isStructInit; - const bool isEnum; - const nonneg int startVarid; + const bool isExecutable{}; + const bool isStructInit{}; + const bool isEnum{}; + const nonneg int startVarid{}; }; } @@ -162,12 +161,7 @@ Tokenizer::Tokenizer(const Settings *settings, ErrorLogger *errorLogger, const P list(settings), mSettings(settings), mErrorLogger(errorLogger), - mSymbolDatabase(nullptr), mTemplateSimplifier(new TemplateSimplifier(*this)), - mVarId(0), - mUnnamedCount(0), - mCodeWithTemplates(false), //is there any templates? - mTimerResults(nullptr), mPreprocessor(preprocessor) { // make sure settings are specified @@ -405,11 +399,10 @@ Token * Tokenizer::deleteInvalidTypedef(Token *typeDef) namespace { struct Space { - Space() : bodyEnd(nullptr), bodyEnd2(nullptr), isNamespace(false) {} std::string className; - const Token * bodyEnd; // for body contains typedef define - const Token * bodyEnd2; // for body contains typedef using - bool isNamespace; + const Token* bodyEnd{}; // for body contains typedef define + const Token* bodyEnd2{}; // for body contains typedef using + bool isNamespace{}; std::set recordTypes; }; } @@ -4022,9 +4015,9 @@ private: std::map mVariableId; std::map mVariableId_global; std::stack>> mScopeInfo; - mutable nonneg int mVarId; + mutable nonneg int mVarId{}; public: - VariableMap() : mVarId(0) {} + VariableMap() = default; void enterScope(); bool leaveScope(); void addVariable(const std::string& varname, bool globalNamespace); diff --git a/lib/tokenize.h b/lib/tokenize.h index f296f10ae..cea8e5132 100644 --- a/lib/tokenize.h +++ b/lib/tokenize.h @@ -698,7 +698,7 @@ private: ErrorLogger* const mErrorLogger; /** Symbol database that all checks etc can use */ - SymbolDatabase *mSymbolDatabase; + SymbolDatabase* mSymbolDatabase{}; TemplateSimplifier * const mTemplateSimplifier; @@ -719,21 +719,21 @@ private: std::vector mTypedefInfo; /** variable count */ - nonneg int mVarId; + nonneg int mVarId{}; /** unnamed count "Unnamed0", "Unnamed1", "Unnamed2", ... */ - nonneg int mUnnamedCount; + nonneg int mUnnamedCount{}; /** * was there any templates? templates that are "unused" are * removed from the token list */ - bool mCodeWithTemplates; + bool mCodeWithTemplates{}; /** * TimerResults */ - TimerResults *mTimerResults; + TimerResults* mTimerResults{}; const Preprocessor * const mPreprocessor; }; diff --git a/lib/tokenlist.cpp b/lib/tokenlist.cpp index 6a8a5edc8..2e023d548 100644 --- a/lib/tokenlist.cpp +++ b/lib/tokenlist.cpp @@ -49,10 +49,7 @@ static const int AST_MAX_DEPTH = 150; TokenList::TokenList(const Settings* settings) : - mTokensFrontBack(), - mSettings(settings), - mIsC(false), - mIsCpp(false) + mSettings(settings) { mTokensFrontBack.list = this; } @@ -396,14 +393,14 @@ std::size_t TokenList::calculateHash() const struct AST_state { std::stack op; - int depth; - int inArrayAssignment; + int depth{}; + int inArrayAssignment{}; bool cpp; - int assign; - bool inCase; // true from case to : - bool stopAtColon; // help to properly parse ternary operators - const Token *functionCallEndPar; - explicit AST_state(bool cpp) : depth(0), inArrayAssignment(0), cpp(cpp), assign(0), inCase(false),stopAtColon(false), functionCallEndPar(nullptr) {} + int assign{}; + bool inCase{}; // true from case to : + bool stopAtColon{}; // help to properly parse ternary operators + const Token* functionCallEndPar{}; + explicit AST_state(bool cpp) : cpp(cpp) {} }; static Token* skipDecl(Token* tok, std::vector* inner = nullptr) diff --git a/lib/tokenlist.h b/lib/tokenlist.h index 68b14523d..a150d36f3 100644 --- a/lib/tokenlist.h +++ b/lib/tokenlist.h @@ -205,11 +205,11 @@ private: std::vector mOrigFiles; /** settings */ - const Settings* mSettings; + const Settings* mSettings{}; /** File is known to be C/C++ code */ - bool mIsC; - bool mIsCpp; + bool mIsC{}; + bool mIsCpp{}; }; /// @} diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index dcadeaee9..2b2b7423e 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -3113,18 +3113,14 @@ struct SingleValueFlowAnalyzer : ValueFlowAnalyzer { struct ExpressionAnalyzer : SingleValueFlowAnalyzer { const Token* expr; - bool local; - bool unknown; - bool dependOnThis; - bool uniqueExprId; + bool local = true; + bool unknown{}; + bool dependOnThis{}; + bool uniqueExprId{}; ExpressionAnalyzer(const Token* e, ValueFlow::Value val, const TokenList& t, const Settings* s) : SingleValueFlowAnalyzer(std::move(val), t, s), - expr(e), - local(true), - unknown(false), - dependOnThis(false), - uniqueExprId(false) + expr(e) { assert(e && e->exprId() != 0 && "Not a valid expression"); @@ -3240,7 +3236,7 @@ struct SameExpressionAnalyzer : ExpressionAnalyzer { }; struct OppositeExpressionAnalyzer : ExpressionAnalyzer { - bool isNot; + bool isNot{}; OppositeExpressionAnalyzer(bool pIsNot, const Token* e, ValueFlow::Value val, const TokenList& t, const Settings* s) : ExpressionAnalyzer(e, std::move(val), t, s), isNot(pIsNot) @@ -3942,23 +3938,21 @@ static void valueFlowForwardLifetime(Token * tok, TokenList &tokenlist, ErrorLog } struct LifetimeStore { - const Token *argtok; + const Token* argtok{}; std::string message; - ValueFlow::Value::LifetimeKind type; + ValueFlow::Value::LifetimeKind type = ValueFlow::Value::LifetimeKind::Object; ErrorPath errorPath; - bool inconclusive; - bool forward; + bool inconclusive{}; + bool forward = true; struct Context { - Token* tok; - TokenList* tokenlist; - ErrorLogger* errorLogger; - const Settings* settings; + Token* tok{}; + TokenList* tokenlist{}; + ErrorLogger* errorLogger{}; + const Settings* settings{}; }; - LifetimeStore() - : argtok(nullptr), message(), type(), errorPath(), inconclusive(false), forward(true), mContext(nullptr) - {} + LifetimeStore() = default; LifetimeStore(const Token* argtok, std::string message, @@ -3967,10 +3961,7 @@ struct LifetimeStore { : argtok(argtok), message(std::move(message)), type(type), - errorPath(), - inconclusive(inconclusive), - forward(true), - mContext(nullptr) + inconclusive(inconclusive) {} template @@ -4055,7 +4046,7 @@ struct LifetimeStore { update = true; } if (update && forward) - forwardLifetime(tok, tokenlist, errorLogger, settings); + forwardLifetime(tok, &tokenlist, errorLogger, settings); return update; } @@ -4150,7 +4141,7 @@ struct LifetimeStore { } } if (update && forward) - forwardLifetime(tok, tokenlist, errorLogger, settings); + forwardLifetime(tok, &tokenlist, errorLogger, settings); return update; } @@ -4226,15 +4217,15 @@ struct LifetimeStore { } private: - Context* mContext; - void forwardLifetime(Token* tok, TokenList& tokenlist, ErrorLogger* errorLogger, const Settings* settings) const { + Context* mContext{}; + void forwardLifetime(Token* tok, TokenList* tokenlist, ErrorLogger* errorLogger, const Settings* settings) const { if (mContext) { mContext->tok = tok; - mContext->tokenlist = &tokenlist; + mContext->tokenlist = tokenlist; mContext->errorLogger = errorLogger; mContext->settings = settings; } - valueFlowForwardLifetime(tok, tokenlist, errorLogger, settings); + valueFlowForwardLifetime(tok, *tokenlist, errorLogger, settings); } }; @@ -4660,12 +4651,6 @@ static void valueFlowLifetimeConstructor(Token* tok, TokenList& tokenlist, Error struct Lambda { explicit Lambda(const Token* tok) - : capture(nullptr), - arguments(nullptr), - returnTok(nullptr), - bodyTok(nullptr), - explicitCaptures(), - implicitCapture(LifetimeCapture::Undefined) { if (!Token::simpleMatch(tok, "[") || !tok->link()) return; @@ -4701,12 +4686,12 @@ struct Lambda { } } - const Token * capture; - const Token * arguments; - const Token * returnTok; - const Token * bodyTok; + const Token* capture{}; + const Token* arguments{}; + const Token* returnTok{}; + const Token* bodyTok{}; std::unordered_map> explicitCaptures; - LifetimeCapture implicitCapture; + LifetimeCapture implicitCapture = LifetimeCapture::Undefined; std::vector getCaptures() const { return getArguments(capture); @@ -6047,7 +6032,7 @@ static void insertNegateKnown(std::list& values, const std::li struct ConditionHandler { struct Condition { - const Token *vartok; + const Token* vartok{}; std::list true_values; std::list false_values; bool inverted = false; @@ -6109,8 +6094,6 @@ struct ConditionHandler { return ctx; } - - Condition() : vartok(nullptr), true_values(), false_values(), inverted(false), impossible(true) {} }; virtual std::vector parse(const Token* tok, const Settings* settings) const = 0; @@ -7168,7 +7151,7 @@ struct MultiValueFlowAnalyzer : ValueFlowAnalyzer { std::unordered_map vars; MultiValueFlowAnalyzer(const std::unordered_map& args, const TokenList& t, const Settings* set) - : ValueFlowAnalyzer(t, set), values(), vars() { + : ValueFlowAnalyzer(t, set) { for (const auto& p:args) { values[p.first->declarationId()] = p.second; vars[p.first->declarationId()] = p.first; diff --git a/lib/valueflow.h b/lib/valueflow.h index 0c0395a37..02e81e660 100644 --- a/lib/valueflow.h +++ b/lib/valueflow.h @@ -72,19 +72,19 @@ namespace ValueFlow { bool isContainerSizeChanged(const Token* tok, int indirect, const Settings* settings = nullptr, int depth = 20); struct LifetimeToken { - const Token* token; + const Token* token{}; Value::ErrorPath errorPath; - bool addressOf; - bool inconclusive; + bool addressOf{}; + bool inconclusive{}; - LifetimeToken() : token(nullptr), errorPath(), addressOf(false), inconclusive(false) {} + LifetimeToken() = default; LifetimeToken(const Token* token, Value::ErrorPath errorPath) - : token(token), errorPath(std::move(errorPath)), addressOf(false), inconclusive(false) + : token(token), errorPath(std::move(errorPath)) {} LifetimeToken(const Token* token, bool addressOf, Value::ErrorPath errorPath) - : token(token), errorPath(std::move(errorPath)), addressOf(addressOf), inconclusive(false) + : token(token), errorPath(std::move(errorPath)), addressOf(addressOf) {} static std::vector setAddressOf(std::vector v, bool b) { diff --git a/lib/vfvalue.cpp b/lib/vfvalue.cpp index 2c1da06cf..6a1ba6f3b 100644 --- a/lib/vfvalue.cpp +++ b/lib/vfvalue.cpp @@ -26,27 +26,10 @@ namespace ValueFlow { Value::Value(const Token *c, long long val, Bound b) - : valueType(ValueType::INT), - bound(b), + : bound(b), intvalue(val), - tokvalue(nullptr), - floatValue(0.0), varvalue(val), - condition(c), - varId(0), - safe(false), - conditional(false), - macro(false), - defaultArg(false), - indirect(0), - moveKind(MoveKind::NonMovedVariable), - path(0), - wideintvalue(0), - subexpressions(), - capturetok(nullptr), - lifetimeKind(LifetimeKind::Object), - lifetimeScope(LifetimeScope::Local), - valueKind(ValueKind::Possible) { + condition(c) { errorPath.emplace_back(c, "Assuming that condition '" + c->expressionString() + "' is not redundant"); } diff --git a/lib/vfvalue.h b/lib/vfvalue.h index a32f86e99..7f7089845 100644 --- a/lib/vfvalue.h +++ b/lib/vfvalue.h @@ -43,28 +43,11 @@ namespace ValueFlow using ErrorPath = std::list; enum class Bound { Upper, Lower, Point }; - explicit Value(long long val = 0, Bound b = Bound::Point) - : valueType(ValueType::INT), + explicit Value(long long val = 0, Bound b = Bound::Point) : bound(b), intvalue(val), - tokvalue(nullptr), - floatValue(0.0), varvalue(val), - condition(nullptr), - varId(0U), - safe(false), - conditional(false), - macro(false), - defaultArg(false), - indirect(0), - moveKind(MoveKind::NonMovedVariable), - path(0), - wideintvalue(val), - subexpressions(), - capturetok(nullptr), - lifetimeKind(LifetimeKind::Object), - lifetimeScope(LifetimeScope::Local), - valueKind(ValueKind::Possible) + wideintvalue(val) {} Value(const Token* c, long long val, Bound b = Bound::Point); @@ -220,7 +203,7 @@ namespace ValueFlow ITERATOR_START, ITERATOR_END, SYMBOLIC - } valueType; + } valueType = ValueType::INT; bool isIntValue() const { return valueType == ValueType::INT; } @@ -275,57 +258,57 @@ namespace ValueFlow } /** The value bound */ - Bound bound; + Bound bound = Bound::Point; /** int value (or sometimes bool value?) */ - long long intvalue; + long long intvalue{}; /** token value - the token that has the value. this is used for pointer aliases, strings, etc. */ - const Token *tokvalue; + const Token* tokvalue{}; /** float value */ - double floatValue; + double floatValue{}; /** For calculated values - variable value that calculated value depends on */ - long long varvalue; + long long varvalue{}; /** Condition that this value depends on */ - const Token *condition; + const Token* condition{}; ErrorPath errorPath; ErrorPath debugPath; /** For calculated values - varId that calculated value depends on */ - nonneg int varId; + nonneg int varId{}; /** value relies on safe checking */ - bool safe; + bool safe{}; /** Conditional value */ - bool conditional; + bool conditional{}; /** Value is is from an expanded macro */ - bool macro; + bool macro{}; /** Is this value passed as default parameter to the function? */ - bool defaultArg; + bool defaultArg{}; - int indirect; + int indirect{}; /** kind of moved */ - enum class MoveKind {NonMovedVariable, MovedVariable, ForwardedVariable} moveKind; + enum class MoveKind { NonMovedVariable, MovedVariable, ForwardedVariable } moveKind = MoveKind::NonMovedVariable; /** Path id */ - MathLib::bigint path; + MathLib::bigint path{}; /** int value before implicit truncation */ - long long wideintvalue; + long long wideintvalue{}; std::vector subexpressions; // Set to where a lifetime is captured by value - const Token* capturetok; + const Token* capturetok{}; enum class LifetimeKind { // Pointer points to a member of lifetime @@ -338,9 +321,9 @@ namespace ValueFlow Iterator, // A pointer that holds the address of the lifetime Address - } lifetimeKind; + } lifetimeKind = LifetimeKind::Object; - enum class LifetimeScope { Local, Argument, SubFunction, ThisPointer, ThisValue } lifetimeScope; + enum class LifetimeScope { Local, Argument, SubFunction, ThisPointer, ThisValue } lifetimeScope = LifetimeScope::Local; static const char* toString(MoveKind moveKind); static const char* toString(LifetimeKind lifetimeKind); @@ -357,7 +340,7 @@ namespace ValueFlow Inconclusive, /** Listed values are impossible */ Impossible - } valueKind; + } valueKind = ValueKind::Possible; void setKnown() { valueKind = ValueKind::Known; diff --git a/test/fixture.cpp b/test/fixture.cpp index 0f7c99bf3..64b1471c4 100644 --- a/test/fixture.cpp +++ b/test/fixture.cpp @@ -79,10 +79,7 @@ std::size_t TestFixture::todos_counter = 0; std::size_t TestFixture::succeeded_todos_counter = 0; TestFixture::TestFixture(const char * const _name) - : mVerbose(false), - exename(), - quiet_tests(false), - classname(_name) + : classname(_name) { TestRegistry::theInstance().addTest(this); } diff --git a/test/fixture.h b/test/fixture.h index dd8264c8c..2a3c26eca 100644 --- a/test/fixture.h +++ b/test/fixture.h @@ -47,7 +47,7 @@ private: static std::size_t fails_counter; static std::size_t todos_counter; static std::size_t succeeded_todos_counter; - bool mVerbose; + bool mVerbose{}; std::string mTemplateFormat; std::string mTemplateLocation; std::string mTestname; @@ -55,7 +55,7 @@ private: protected: std::string exename; std::string testToRun; - bool quiet_tests; + bool quiet_tests{}; virtual void run() = 0; diff --git a/test/testtoken.cpp b/test/testtoken.cpp index f6c408ad0..60f03db1a 100644 --- a/test/testtoken.cpp +++ b/test/testtoken.cpp @@ -481,7 +481,7 @@ private: } void deleteLast() const { - TokensFrontBack listEnds{ nullptr }; + TokensFrontBack listEnds; Token ** const tokensBack = &(listEnds.back); Token tok(&listEnds); tok.insertToken("aba"); @@ -491,7 +491,7 @@ private: } void deleteFirst() const { - TokensFrontBack listEnds{ nullptr }; + TokensFrontBack listEnds; Token ** const tokensFront = &(listEnds.front); Token tok(&listEnds);