Skip to content

Note/Why should the getInstance() method of a Singleton return a reference? #12

@onur-ulusoy

Description

@onur-ulusoy

Problem Description

Singleton design pattern is implemented to child device classes successfully:

static GPIO_Device& getInstance(char* dev_name){
    static GPIO_Device instance(dev_name);
    return instance;
}

However it turns out to be a syntax error if it returns the actual object (namely call by value) instead of reference

static GPIO_Device getInstance(char* dev_name){
    static GPIO_Device instance(dev_name);
    return instance;
}

Problem Reason

When it called by value like below,

GPIO_Device gpio = GPIO_Device::getInstance(dev_name);    

Because it returns actual object and be assigned to a new object from GPIO_Device, copy constructor of the class is invoked and since the copy constructor of class is deleted it causes syntax error.

Fundamental Reason to Use Reference

In a Singleton pattern, the goal is to ensure that there is only one instance of a class. Returning a reference or pointer to that instance, instead of an object, helps ensure that there is only one instance of the class in the entire system. This allows other parts of the system to access the Singleton without accidentally creating new instances of it.

Calling it by value is against the nature of Singleton pattern cause it creates more than one object.

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions