Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
onur-ulusoy opened this issue Mar 30, 2023 · 0 comments
Labels
documentation Improvements or additions to documentation

Comments

@onur-ulusoy
Copy link
Owner

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.

@onur-ulusoy onur-ulusoy added the documentation Improvements or additions to documentation label Mar 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

1 participant