I have a private static vector in my class that keeps a pointer to all objects created from it. It's necessary as each object needs access to information from all the other objects to perform some calculations:
// Header file:
class Example {
public:
Example();
private:
static std::vector<const Example*> examples_;
};
// Cpp file:
std::vector<const Example *> Example::examples_ = {};
Example::Example() {
// intialization
examples_.emplace_back(this);
}
void Example::DoCalc() {
for (auto example : examples_) {
// do stuff
}
}
clang-tidy
points out that I'm violating C++ Core Guidelines, namely : "Variable 'examples_' is non-const and globally accessible, consider making it const (cppcoreguidelines-avoid-non-const-global-variables)".
Personally, I don't see the resemblance between my code and the sample code in the core guidelines, especially since the variable is inside a class and private. What would be the 'correct' way of implementing this functionality? I don't want to disable this check from clang-tidy if it can be avoided.
static inline std::vector<const Example*> examples_;
in the class and then removestd::vector<Example *> Example::examples_ = {};
from the cpp file. Do you still get the warning? – Sniffconst
here:std::vector<const Example *> Example::examples_ = {};
. But I guess it is just a typo and not your real problem. – Extrauterinethis
fromexamples_
, and copy and move constructors, otherwiseexamples_
isn't "all objects created from it" – Recipience