Error: 'std :: ios_base :: ios_base (const std :: ios_base &) is private

#include <iostream> #include <fcntl.h> #include <fstream> using namespace std; class Logger { private: ofstream debug; Logger() { debug.open("debug.txt"); } static Logger log; public: static Logger getLogger() { return log; } void writeToFile(const char *data) { debug << data; } void close() { debug.close(); } }; Logger Logger::log; 

Through this class, I am trying to create a Logger class that goes into a file. But this gives an error, for example,

 error: 'std::ios_base::ios_base(const std::ios_base&)' is private 

I took it apart and found that it was due to thread copying. As far as I understand in this code, copying of streams does not occur.

Can the guys help me. Thanks in advance.

~

+4
source share
1 answer
 static Logger getLogger() { return log; } 

tries to return a Logger value by a value that requires a copy constructor. The creator created by the compiler is trying to make a copy of the debug element. That is why you get an error.

You can either implement the copy constructor (it may not make sense, since the debug member will be different) or return by reference:

 static Logger& getLogger() { return log; } 

which is safe in this case, because log has a static storage duration .

The correct call would look like this:

 Logger& l = Logger::getLogger(); 

in this case, l refers to Logger::log .

+6
source

Source: https://habr.com/ru/post/1440491/


All Articles