0

I want to have a static variable, such that I can assign a std::shared_ptr object to it when I construct the class. What I tried was the following which did not work.

class CLS
{
    static std::shared_ptr<spdlog::logger> log;
    static unsigned int p;

public:
    CLS(const unsigned int input1 = 1,
        const std::shared_ptr<spdlog::logger>& logger=nullptr)

    {
       if (logger != nullptr) {
          log            = logger;
       }
       p = input1;
    }
    ~CLS()
    {
    }
};

I could do it for example for and integer object like above but not shared_ptr.

The reason I want this is that for a functionality, when I construct this class without the "logger" input, I want the "log" static variable to be available for use.

Alejandro
  • 879
  • 11
  • 27
  • what do you mean by "did not work"? A compilation error or something else? – PiotrNycz Oct 28 '21 at 12:52
  • Are you sure you want those two attributes to be `static`? This does not look like a good design... – Holt Oct 28 '21 at 12:55
  • Why `static`? Why a `shared_ptr` (with its thread-safety overhead, which will be, however, rendered useless by using the same instance instead of multiple copies) instead of just a `unique_ptr`? Is the class guaranteed to be a singleton? What owns the `logger` instance? It may be better to describe *what* you want to accomplish rather than *how*… – Andrej Podzimek Oct 28 '21 at 12:55
  • @PiotrNycz not compiled. it says undefined reference to `CLS::log' – Alejandro Oct 28 '21 at 12:58
  • @Holt I am not sure, but do I have a chance with not static? I try the non-static as well – Alejandro Oct 28 '21 at 12:59
  • Please include the error message with your non-working code. The error message tells you exactly what is wrong, and helps us help you. – NathanOliver Oct 28 '21 at 12:59

0 Answers0