Reputation: 15
I was going through one of the examples of C++, for cloning of an object.
#ifndef CLIPBOARDSTACK_H
#define CLIPBOARDSTACK_H
#include <QStack>
#include "getEntity.h"
class clipboardStack
{
public:
static clipboardStack *instance()
{
if (!inst)
inst = new clipboardStack;
return inst;
}
void push(getEntity *entity)
{
clips.push(entity);
}
getEntity *pasteEntity()
{
if (clips.count() == 0)
return 0;
return clips.last();
}
getEntity *pop()
{
if (clips.count() == 0)
return 0;
return clips.pop();
}
bool isEmpty() const
{
return clips.empty();
}
private:
QStack<getEntity *> clips;
static clipboardStack *inst;
};
#endif // CLIPBOARDSTACK_H
where getEntity is:
#ifndef GETENTITY_H
#define GETENTITY_H
#include <QGraphicsItem>
class getEntity : public QObject, public QGraphicsItem
{
public:
getEntity(QObject *parent = 0) : QObject(parent) {}
virtual ~getEntity() {}
virtual getEntity *clone()
{
return 0;
}
};
#endif // GENTITY_H
But I couldn't get what exactly the line means.
What is the meaning of the line:
static clipboardStack *instance()
{
if (!inst)
inst = new clipboardStack;
return inst;
}
Can someone explain me what does above line exactly do, and the two classes in brief?
Upvotes: 1
Views: 100
Reputation: 10733
static clipboardStack *instance()
{
if (!inst)
inst = new clipboardStack;
return inst;
}
This is a code for singleton pattern. If there is no instance of class clipboardStack, then it would create it else it would return already created instance.
NOTE:- This implementation of singleton is not thread-safe.
Upvotes: 3
Reputation: 437
static clipboardStack *instance() { if (!inst) inst = new clipboardStack;
return inst;
}
This is singleton pattern, usually they write this pattern for having only one instance of the class at any point of time.
If there is no instance for the clipboardstack created. you just create one. next time when someone calls instance(), it delivers the same instance created before. No new instance gets created again.
I guess you have to initialize the clipboardstack pointer to NULL. Its a good programming practice. If you are in a debug mode this might point to uninitialized memory like 0xCDCDCD for instance, which is not null and everytime you call instance(), you will get 0xCDCDCD and you will end up crashing the program.
Upvotes: 0