Home > Net >  Can access private sections in Singleton class
Can access private sections in Singleton class

Time:03-16

I wrote an singletone class as below:

class logger
{
    FILE *__fp_log = NULL;
    const char* __logpath;
    //Constructor
    logger();
    static logger* __instance;
    logger& operator=(const logger &) ;
    logger(const logger &);
public:
    ~logger();
    void write_file( const char* ,... );
    static logger* getInstance();
};

I understand that I need to make Copy Constructor and assignment operator as private (reference here). But still I can access them from main():

logger* log = logger::getInstance();
logger* log2 = logger::getInstance();

log = logger::getInstance();

I should get a compilation warning, any pointer why compilation is not complaining? I am compiling using g :

g   .\main.cpp .\logger.cpp

CodePudding user response:

You're not performing any copying or assignment of loggers here. You're copying/assigning pointers to logger, which doesn't involve the logger object being pointed to at all.

The operation you're trying to prohibit would be something like:

 logger log = *logger::getInstance();  // Dereferencing and copying to separate log object

which would try to make an unrelated instance that is a copy of the singleton instance.

Analogy: Your house is unique. No one can make an exact copy of your house (at least, it's unreasonably difficult to do so) without access to the blueprints (the constructor). But someone who has the address of your house can easily copy the address to a postcard, without affecting your house in any way. Your getInstance() method is returning a copy of the address, which you can "write" to a "postcard" (a local pointer to logger). It does not affect the "house" (the singleton logger instance) in any way. Any such copy of the address can be used to find the "house"/logger instance, but by making the constructors and assignment operator private, you've denied access to the house's blueprints (constructor/assignment), so they're limited to walking around your "house" (calling methods on the singleton logger), they can't just make a duplicate of it.

  •  Tags:  
  • c
  • Related