Please consider the following code: #ifndef STATEFACTORYHPP #define STATEFACTORYHPP…
- User
Please consider the following code: #ifndef STATE_FACTORY_HPP #define STATE_FACTORY_HPP
#include <unordered_map> #include #include
#include "Interface.hpp"
class StateFactory { public: using CreateFunc = std::function<std::unique_ptr(std::shared_ptr)>;
codestatic StateFactory &instance() { static StateFactory factory; // first warning return factory; } void registerState(const std::string &name, CreateFunc func) // second warning { if (auto it = creators.find(name); it == creators.end()) { creators[name] = func; return; } throw std::invalid_argument("State already registered: " + name); } std::unique_ptr<State> create(const std::string &name) const { if (!linked) throw std::invalid_argument("Configuration not linked"); if (auto it = creators.find(name); it != creators.end()) { return it->second(fullConfig); } throw std::invalid_argument("State not found: " + name); } void linkConfiguration(std::shared_ptr<IFullConfiguration> fullConfig_) { if (linked) throw std::invalid_argument("Configuration already linked"); fullConfig = fullConfig_; if (!fullConfig) throw std::invalid_argument("Invalid or undefined state"); linked = true; }private: std::unordered_map<std::string, CreateFunc> creators; // third warning
codeStateFactory() = default; StateFactory(const StateFactory &) = delete; StateFactory &operator=(const StateFactory &) = delete; std::shared_ptr<IFullConfiguration> fullConfig; bool linked = false;};
#endif Sonarlint warns about:
- Use inline variables to define this global variable.sonarlint(cpp:S6018)
- Assistant
- User
The first solution does not work: indeed, the compiler returns: incomplete type "StateFactory" is not allowed, in the private member. I think because at that point StateFactory is not complete declared.
- Assistant
You're correct; the issue arises because the complete definition of
StateFactoryis not known at the point where you are trying to declareinline static StateFactory factory;. Theinlinekeyword in class definitions indeed requires a complete type.Here's a revised approach to achieve the same objective:
- Use an
inlinefunction to access the static instance. Instead of moving outside the class, keep it local to the method:
- Use an