Use in-class initializers, default constructors, class -> struct (#4842)

This commit is contained in:
chrchr-github 2023-08-08 11:05:02 +02:00 committed by GitHub
parent 838b6b86e3
commit eee1221738
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
80 changed files with 531 additions and 861 deletions

View File

@ -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:

View File

@ -37,18 +37,16 @@ These are coding guidelines we do not follow. Some of the checks might be explic
`modernize-use-auto`<br>
`readability-uppercase-literal-suffix`<br>
`readability-else-after-return`<br>
`modernize-use-default-member-init`<br>
`readability-identifier-length`<br>
These do not relect the style we are (currently) enforcing.
These do not reflect the style we are (currently) enforcing.
`readability-function-size`<br>
`readability-function-cognitive-complexity`<br>
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`<br>
`readability-redundant-member-init`<br>
These do not (always) increase readability.
@ -58,7 +56,7 @@ To be documented.
`readability-implicit-bool-conversion`<br>
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`<br>
`performance-no-automatic-move`<br>

View File

@ -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)

View File

@ -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;
};

View File

@ -72,10 +72,6 @@
/*static*/ FILE* CppCheckExecutor::mExceptionOutput = stdout;
CppCheckExecutor::CppCheckExecutor()
: mSettings(nullptr), mLatestProgressOutputTime(0), mErrorOutput(nullptr), mShowAllErrors(false)
{}
CppCheckExecutor::~CppCheckExecutor()
{
delete mErrorOutput;

View File

@ -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

View File

@ -85,7 +85,7 @@ class ThreadData
{
public:
ThreadData(ThreadExecutor &threadExecutor, ErrorLogger &errorLogger, const Settings &settings, const std::map<std::string, std::size_t> &files, const std::list<ImportProject::FileSettings> &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<ImportProject::FileSettings> &mFileSettings;
std::list<ImportProject::FileSettings>::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;

View File

@ -27,8 +27,7 @@
#include <QVariant>
ApplicationList::ApplicationList(QObject *parent) :
QObject(parent),
mDefaultApplicationIndex(-1)
QObject(parent)
{
//ctor
}

View File

@ -133,7 +133,7 @@ private:
* @brief Index of the default application.
*
*/
int mDefaultApplicationIndex;
int mDefaultApplicationIndex = -1;
};
/// @}
#endif // APPLICATIONLIST_H

View File

@ -84,10 +84,8 @@ static bool executeCommand(std::string exe, std::vector<std::string> args, std::
CheckThread::CheckThread(ThreadResult &result) :
mState(Ready),
mResult(result),
mCppcheck(result, true, executeCommand),
mAnalyseWholeProgram(false)
mCppcheck(result, true, executeCommand)
{
//ctor
}

View File

@ -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<Suppressions::Suppression> mSuppressions;

View File

@ -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)),

View File

@ -81,7 +81,7 @@ public:
static void saveSettings(QSettings *settings, const CodeEditorStyle& theStyle);
public:
bool mSystemTheme;
bool mSystemTheme{};
QColor widgetFGColor;
QColor widgetBGColor;
QColor highlightBGColor;

View File

@ -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<int>(QFont::Thin)));

View File

@ -71,7 +71,7 @@ public slots:
void changeWeight(int index);
private:
QFont::Weight mWeight;
QFont::Weight mWeight = QFont::Normal;
};
#endif //CODEEDITORSTYLECONTROLS_H

View File

@ -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<struct MinSize> 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> codeBlocks;
@ -232,12 +203,8 @@ public:
};
struct SmartPointer {
SmartPointer() :
unique {false}
{}
QString name;
bool unique;
bool unique{};
};
struct Entrypoint {

View File

@ -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 {

View File

@ -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);

View File

@ -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();

View File

@ -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;

View File

@ -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.

View File

@ -23,7 +23,6 @@
#include <QIODevice>
Report::Report(QString filename) :
QObject(),
mFilename(std::move(filename))
{}

View File

@ -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

View File

@ -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

View File

@ -67,7 +67,6 @@
ResultsView::ResultsView(QWidget * parent) :
QWidget(parent),
mShowNoErrorsMessage(true),
mUI(new Ui::ResultsView),
mStatistics(new CheckStatistics(this))
{

View File

@ -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;

View File

@ -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);

View File

@ -73,7 +73,7 @@ private slots:
void pdfExport();
private:
Ui::StatsDialog *mUI;
const CheckStatistics *mStatistics;
const CheckStatistics* mStatistics{};
};
/// @}

View File

@ -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;

View File

@ -36,11 +36,7 @@
#include <QVariant>
ThreadHandler::ThreadHandler(QObject *parent) :
QObject(parent),
mScanDuration(0),
mRunningThreadCount(0),
mAnalyseWholeProgram(false)
QObject(parent)
{
setThreadCount(1);
}

View File

@ -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<Suppressions::Suppression> mSuppressions;

View File

@ -28,11 +28,6 @@
#include <QFile>
#include <QMutexLocker>
ThreadResult::ThreadResult() : QObject(), ErrorLogger(), mMaxProgress(0), mProgress(0), mFilesChecked(0), mTotalFiles(0)
{
//ctor
}
ThreadResult::~ThreadResult()
{
//dtor

View File

@ -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

View File

@ -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

View File

@ -135,7 +135,7 @@ private:
* @brief Translator class instance.
*
*/
QTranslator *mTranslator;
QTranslator* mTranslator{};
};
/// @}

View File

@ -32,7 +32,7 @@ class ValuePtr;
struct Analyzer {
struct Action {
Action() : mFlag(0) {}
Action() = default;
template<class T,
REQUIRES("T must be convertible to unsigned int", std::is_convertible<T, unsigned int> ),
@ -125,7 +125,7 @@ struct Analyzer {
}
private:
unsigned int mFlag;
unsigned int mFlag{};
};
enum class Terminate { None, Bail, Escape, Modified, Inconclusive, Conditional };

View File

@ -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) {

View File

@ -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) {

View File

@ -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<std::string> 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);

View File

@ -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;

View File

@ -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,

View File

@ -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

View File

@ -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<std::string, FunctionUsage> mFunctions;

View File

@ -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");
}

View File

@ -205,10 +205,10 @@ static std::vector<std::string> 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;

View File

@ -391,10 +391,7 @@ CppCheck::CppCheck(ErrorLogger &errorLogger,
bool useGlobalSuppressions,
std::function<bool(std::string,std::vector<std::string>,std::string,std::string&)> executeCommand)
: mErrorLogger(errorLogger)
, mExitCode(0)
, mUseGlobalSuppressions(useGlobalSuppressions)
, mTooManyConfigs(false)
, mSimplify(true)
, mExecuteCommand(std::move(executeCommand))
{}

View File

@ -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<Check::FileInfo*> mFileInfo;

View File

@ -158,7 +158,6 @@ std::string CTU::toString(const std::list<CTU::FileInfo::UnsafeUsage> &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)

View File

@ -51,15 +51,15 @@ struct ForwardTraversal {
enum class Progress { Continue, Break, Skip };
enum class Terminate { None, Bail, Inconclusive };
ForwardTraversal(const ValuePtr<Analyzer>& analyzer, const Settings& settings)
: analyzer(analyzer), settings(settings), actions(Analyzer::Action::None), analyzeOnly(false), analyzeTerminate(false)
: analyzer(analyzer), settings(settings)
{}
ValuePtr<Analyzer> analyzer;
const Settings& settings;
Analyzer::Action actions;
bool analyzeOnly;
bool analyzeTerminate;
bool analyzeOnly{};
bool analyzeTerminate{};
Analyzer::Terminate terminate = Analyzer::Terminate::None;
std::vector<Token*> loopEnds = {};
std::vector<Token*> loopEnds;
Progress Break(Analyzer::Terminate t = Analyzer::Terminate::None) {
if ((!analyzeOnly || analyzeTerminate) && t != Analyzer::Terminate::None)

View File

@ -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<KnownAndToken> mValueFlow;
bool mValueFlowKnown;
bool mValueFlowKnown = true;
};
#endif // fwdanalysisH

View File

@ -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;
};

View File

@ -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<std::string> includePaths;
std::list<std::string> 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);

View File

@ -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) {

View File

@ -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<std::string, Function> functions;
int type_templateArgNo;
int type_templateArgNo = -1;
std::vector<RangeItemRecordTypeItem> 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<std::string, Function>::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<MinSize> 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<int, ArgumentChecks> 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<std::string> mBlocks;
};
enum class FalseTrueMaybe { False, True, Maybe };
int mAllocId;
int mAllocId{};
std::set<std::string> mFiles;
std::map<std::string, AllocFunc> mAlloc; // allocation functions
std::map<std::string, AllocFunc> mDealloc; // deallocation functions

View File

@ -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;

View File

@ -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);

View File

@ -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)
{

View File

@ -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);

View File

@ -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<std::string> 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<std::string> 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<std::string> 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<std::string> 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<std::string> 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> 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<std::string> 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

View File

@ -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") {

View File

@ -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 };
};

View File

@ -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) {

View File

@ -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<BaseInfo> derivedFrom;
std::vector<FriendInfo> 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<Dimension> 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<Variable> 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<Function> functionList;
std::multimap<std::string, const Function *> functionMap;
std::list<Variable> varlist;
const Scope *nestedIn;
const Scope* nestedIn{};
std::vector<Scope *> nestedList;
nonneg int numConstructors;
nonneg int numCopyOrMoveConstructors;
nonneg int numConstructors{};
nonneg int numCopyOrMoveConstructors{};
std::vector<UsingInfo> usingList;
ScopeType type;
Type* definedType;
ScopeType type{};
Type* definedType{};
std::map<std::string, Type*> definedTypesMap;
std::vector<const Token *> 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<Enumerator> 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);

View File

@ -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()

View File

@ -500,7 +500,7 @@ private:
TokenList &mTokenList;
const Settings &mSettings;
ErrorLogger *mErrorLogger;
bool mChanged;
bool mChanged{};
std::list<TokenAndName> mTemplateDeclarations;
std::list<TokenAndName> mTemplateForwardDeclarations;

View File

@ -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)
{}

View File

@ -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

View File

@ -56,12 +56,7 @@ namespace {
const std::list<ValueFlow::Value> TokenImpl::mEmptyValueList;
Token::Token(TokensFrontBack *tokensFrontBack) :
mTokensFrontBack(tokensFrontBack),
mNext(nullptr),
mPrevious(nullptr),
mLink(nullptr),
mTokType(eNone),
mFlags(0)
mTokensFrontBack(tokensFrontBack)
{
mImpl = new TokenImpl();
}

View File

@ -39,7 +39,7 @@
#include <utility>
#include <vector>
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<std::string> usingNamespaces_ = std::set<std::string>()) : name(std::move(name_)), bodyEnd(bodyEnd_), usingNamespaces(std::move(usingNamespaces_)) {}
std::string name;
const Token * const bodyEnd;
const Token* const bodyEnd{};
std::set<std::string> 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<ValueFlow::Value>* mValues;
std::list<ValueFlow::Value>* mValues{};
static const std::list<ValueFlow::Value> mEmptyValueList;
// Pointer to a template in the template simplifier
std::set<TemplateSimplifier::TokenAndName*>* mTemplateSimplifierPointers;
std::set<TemplateSimplifier::TokenAndName*>* mTemplateSimplifierPointers{};
// Pointer to the object representing this token's scope
std::shared_ptr<ScopeInfo2> 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.

View File

@ -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<std::string> recordTypes;
};
}
@ -4022,9 +4015,9 @@ private:
std::map<std::string, nonneg int> mVariableId;
std::map<std::string, nonneg int> mVariableId_global;
std::stack<std::vector<std::pair<std::string, nonneg int>>> 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);

View File

@ -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<TypedefInfo> 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;
};

View File

@ -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<Token*> 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<Token*>* inner = nullptr)

View File

@ -205,11 +205,11 @@ private:
std::vector<std::string> mOrigFiles;
/** settings */
const Settings* mSettings;
const Settings* mSettings{};
/** File is known to be C/C++ code */
bool mIsC;
bool mIsCpp;
bool mIsC{};
bool mIsCpp{};
};
/// @}

View File

@ -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<class F>
@ -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<const Variable*, std::pair<const Token*, LifetimeCapture>> explicitCaptures;
LifetimeCapture implicitCapture;
LifetimeCapture implicitCapture = LifetimeCapture::Undefined;
std::vector<const Token*> getCaptures() const {
return getArguments(capture);
@ -6047,7 +6032,7 @@ static void insertNegateKnown(std::list<ValueFlow::Value>& values, const std::li
struct ConditionHandler {
struct Condition {
const Token *vartok;
const Token* vartok{};
std::list<ValueFlow::Value> true_values;
std::list<ValueFlow::Value> 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<Condition> parse(const Token* tok, const Settings* settings) const = 0;
@ -7168,7 +7151,7 @@ struct MultiValueFlowAnalyzer : ValueFlowAnalyzer {
std::unordered_map<nonneg int, const Variable*> vars;
MultiValueFlowAnalyzer(const std::unordered_map<const Variable*, ValueFlow::Value>& 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;

View File

@ -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<LifetimeToken> setAddressOf(std::vector<LifetimeToken> v, bool b) {

View File

@ -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");
}

View File

@ -43,28 +43,11 @@ namespace ValueFlow
using ErrorPath = std::list<ErrorPathItem>;
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<std::string> 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;

View File

@ -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);
}

View File

@ -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;

View File

@ -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);