Reputation: 17295
Most of my experience with OOP comes from Objective-C
. In that language there's a clear distinction between instance and class methods. As a result it is fairly easy to work with a singleton without any side effects.
In C++
I haven't been that lucky and I can't seem to avoid objects being created out of my control.
I have the following object
class Window
{
private:
Window();
Window(Window const &windowCopy);
void operator=(Window const &windowRight);
public:
~Window();
static Window getSingleton();
};
This is the .h
. Most of the implementation is just me using cout
to print messages when each method in the .h
is being called. Except for the getSingleton()
method.
Window Window::getSingleton()
{
static Window singleton;
return singleton;
}
And here's my main
int main(int argc, char *argv[])
{
Window::getSingleton();
Window::getSingleton();
std::cout << "Stack is being removed" << std::endl;
return 0;
}
After running this I get the following output
Window created -> 0x10c9bf0e0 // This is the static singleton
Window copied -> 0x7fff53242bb8 <- from 0x10c9bf0e0 // What is this?
Window destroyed -> 0x7fff53242bb8 // And what is it's scope?
Window copied -> 0x7fff53242bb0 <- from 0x10c9bf0e0
Window destroyed -> 0x7fff53242bb0
Stack is being removed
Window destroyed -> 0x10c9bf0e0
For some reason whenever I call my singleton method, a new object appears and the singleton gets assigned to itself. Why? And how can I change this so that there's only one Window
object for the entire duration of the app?
Upvotes: 1
Views: 121
Reputation: 43662
You're passing the object by value
Window Window::getSingleton()
{
static Window singleton;
return singleton;
}
you should return it by reference (or a pointer to it) instead
Window& Window::getSingleton()
{
static Window singleton;
return singleton;
}
That is usually the intended behavior of the singleton pattern.
Upvotes: 5