Using a Static Class function to create a Singleton object/instance - c++

I am trying to create a static member function that returns a pointer to one instance of the class. Is this possible in C++?
class DynamicMemoryLog
{
// Singleton Class:
public:
static DynamicMemoryLog* CreateLog();
void AddIObject( IUnknown* obj );
void ReleaseDynamicMemory();
private:
// static DynamicMemoryLog* instance;
static bool isAlive; // used to determine is an instance of DynamicMemoryLog already exists
DynamicMemoryLog();
~DynamicMemoryLog();
std::vector <IUnknown*> iObjectList;
};
This function below should create a new instance of the class & return a pointer to that object, but the compiler will not allow me to define a static function of the class if it returns a pointer(I think thats why it wont compile?):
static DynamicMemoryLog* DynamicMemoryLog :: CreateLog()
{
// Post:
if ( !isAlive ) // ( instance == NULL; )
{
DynamicMemoryLog* instance = new DynamicMemoryLog();
return instance;
}
return NULL;
}

The particular error you're getting is that when implementing a static member function, you don't repeat the static keyword. Fixing this should resolve the error.
Independently, there's something a bit odd with your code. You claim that this object is a singleton, but each call to CreateLog will create a new instance of the class. Do you really want this behavior, or do you want there to be many copies? I'd suggest looking into this before proceeding.

Here's the simplest solution, but not thread-safe. For analysis in detail, have a look at this article.
class DynamicMemoryLog
{
public:
static DynamicMemoryLog* GetInstance();
private:
DynamicMemoryLog();
static DynamicMemoryLog* m_pInstance;
}
DynamicMemoryLog* DynamicMemoryLog::GetInstance()
{
if(!m_pInstance)
{
m_pInstance = new DynamicMemoryLog();
}
return m_pInstance;
}

I usually do something like this:
class Singleton
{
public:
static Singleton* get()
{
static Singleton instance;
return &instance;
}
};
This way you won't have any nasty memory management issues.

Related

How do I create a destroyable threadsafe singleton C++?

class Singleton
{
static std::shared_ptr<Singleton> GetInstance()
{
static std::shared_ptr<Singleton> instance = make_shared<Singleton>();
retrun instance;
}
static void DestroyInstance()
{
// What goes in here?
}
}
The reason I pass around a sharedPtr is because I don't want others to take a lock while using the Singleton in their code with the fear that it might get destroyed in a parallel thread. I can gurantee that they won't hold on to it for ever. So when DestroyInstance is called I just want the static shared_ptr<Singleton> to reduce count by one and when everyone else lets are done with their singleton it'll eventualy get destroyed. Also I'd want it such that once the Singleton is destroyed it can never be created again with GetInstance and it should simply return a nullptr.
Your other function would have to get access to a reference to the static object somehow.
What I would do is to hide the instance function privately and return a reference. The public function would return the copy of the shared pointer as usual.
struct Singleton {
static auto GetInstance() -> std::shared_ptr<Singleton> {
return GetRef();
}
static auto DropInstance() -> void {
GetRef() = nullptr;
}
private:
static auto GetRef() -> std::shared_ptr<Singleton>& {
static auto instance = std::make_shared<Singleton>();
return instance;
}
};

Is there a way to get class object in static function other than passing it as parameter?

Is there a way to get the class object in a class static function other than passing it as function argument? I cannot pass it as argument or make my class singleton.
class test{
public:
int i=10;
test(){}
Static test_static_method(){
// somehow get an object of the class to call class member.
std::cout << classObj->i << "\n";
}
};
I am trying to pass the static function to a C-API that takes in void(*)(). But I need class instance in my function to access the class data. Any help is appreciated.
If you're not going to have too many instances of your class, you can use preallocated "callback pool" -- pre-created functions that you allocate as needed for the callbacks:
#define REP10(P, M) M(P##0) M(P##1) M(P##2) M(P##3) M(P##4) M(P##5) M(P##6) M(P##7) M(P##8) M(P##9)
#define REP100(M) REP10(,M) REP10(1,M) REP10(2,M) REP10(3,M) REP10(4,M) REP10(5,M) REP10(6,M) REP10(7,M) REP10(8,M) REP10(9,M)
typedef void (*callback_fn_t)(void); // or whatever signature you need
class myclass {
static struct callback_t {
callback_t *next;
callback_fn_t callback;
myclass *obj;
} callback_table[100];
callback_t *my_callback;
static callback_t *freelist;
#define CB_FUNC_DECL(M) static void cbfunc##M() { callback_table[M].obj->callback(); }
REP100(CB_FUNC_DECL)
public:
callback_fn_t get_callback() {
if (!my_callback) {
if (!freelist) return nullptr;
my_callback = freelist;
freelist = my_callback->next;
my_callback->obj = this; }
return my_callback->callback;
}
void callback() {
/* this non-static method is called by the callback */
}
myclass() : my_callback(nullptr) { }
myclass(const myclass &a) : my_callback(nullptr) {
// need to manually define copy
}
~myclass() {
if (my_callback) {
my_callback->obj = nullptr;
my_callback->next = freelist;
freelist = my_callback; }
}
};
#define CB_TABLE_INIT(M) { M ? myclass::callback_table+M-1 : 0, myclass::cbfunc##M },
myclass::callback_t myclass::callback_table[100] = { REP100(CB_TABLE_INIT) };
myclass::callback_t *myclass::freelist = &myclass::callback_table[99];
Now if you want to use one of these objects as a callback, you call get_callback to get the function pointer you give to the C library, and it will call the callback method in your class on that object.
** I offer here an addition of a singleton solution although you said you can't, for future readers of this topic, who might see it helpful. Pay attention to the other solution.
The answer to your question is "No" for a reason. Objects are unique, and any object of the same class can (and usually will) contains a different data. When you are talking about static function/members of a class, different objects of the same class, will always contain the exact same data in those static functions/members.
However, if from some reason (probably an architecture bug), you don't care which object you will access using your static function, you can either make your class a singleton (which means that you'll always have only one instance of your class, and you'll always know which object data you'll use), or define an object instance static pointer in your class. Something like that:
class test {
public:
int i = 10;
test *class_obj;
test() {
class_obj = this; // The last object that created
}
Static test_static_method() {
// somehow get an object of the class to call class member.
std::cout << class_obj->i << "\n";
}
};
Read about:
Singleton
C++ Singleton
Static members in C++

How to prevent a caller of a method from storing the result in C++

Assume I have a Singleton class. How can I prevent callers from being able to store the result of the call to getInstance() method?
I need this, since the instance of the singleton can be modified during execution and any stored instance in other classes will be invalidated. My solution would be to force all the callers to call getInstance() every time when they want to use the instance of the Singleton.
class Singleton
{
private:
static Singleton* instance;
private:
Singleton();
public:
static Singleton* getInstance();
};
Singleton* Singleton::instance = nullptr;
Singleton* Singleton::getInstance()
{
if (instance == nullptr)
{
instance = new Singleton();
}
return instance;
}
class A
{
private:
Singleton* m_singleton;
public:
A()
: m_singleton(Singleton::getInstance()) //This should not be possible
{
}
};
int main()
{
A a;
return 0;
}
How can I achieve this?
You cannot. If your getInstance() returns a pointer or reference, there is no way to prevent the result from being copied into some variable, the same way as you cannot prevent a result of type int or double from being copied.
You could, however, make the functions the singleton provides static:
class SomeSingleton
{
public:
static void foo();
private:
// deleting copy constructor and assignment operator...
static SomeSingleton* getInstance();
};
void SomeSingleton::foo()
{
SomeSingleton* instance = getInstance();
// use instance as you need to get the appropriate result
}
So you enforce usage like this:
SomeSingleton::foo();
Some might even consider it more comfortable to use than
SomeSingleton::getInstance().foo();
By the way: This aproach makes it possible to protect you from race conditions, too, if multi-threading is or gets an issue:
class SomeSingleton
{
public:
static void foo();
private:
static std::mutex mutex; // <- add a mutex!
static SomeSingleton* getInstance();
static void exchange();
};
void SomeSingleton::foo()
{
// this must be added whenever the singleton is used...
std::lock_guard<std::mutex> guard(mutex);
SomeSingleton* instance = getInstance();
// use instance as you need to get the appropriate result
}
void SomeSingleton::exchange()
{
// ... or the singleton instance is re-asigned
std::lock_guard<std::mutex> guard(mutex);
SomeSingleton* newInstance = new SomeSingleton();
delete instance;
instance = newInstance;
}
My solution is a wrapper with overloaded -> operator like in smart pointers which calls getInstance() inside:
class Singleton {
friend SingletonWrapper;
private:
static Singleton * getInstance() {...}
public:
void foo() {}
};
class SingletonWrapper {
public:
Singleton * operator->() {
return Singleton::getInstance();
}
};
int main() {
SingletonWrapper w;
w->foo();
}
First of all I wouldn't suggest using pointers for singletons. This ("Meyer Singleton") is a much better approach.
static SingletonDatabase &get() {
static SingletonDatabase db;
return db;
}
Also storing the singleton is kind of a bad idea, as with the storing you validate the initial idea / purpose behind the singleton: You are making copies, thus the singleton is not the "sole" instance of the class.
Anyway a great solution to your problem would be to use some kind of signal/slot system. (Qt / Boost library) Upon change you can emit the singal, which is then "caught" by all instances and the actualize the values.
Boost Signals / Slots
Qt Signals Slots
I Hope this helps :)
Use volatile to declare the singleton variable. This will force the compiler to always check for it
class Singleton
{
private:
static volatile Singleton* instance;
private:
Singleton();
public:
static volatile Singleton* getInstance();
};

Single Instance

I am new to object oriented programming in C++, and well, it hasn't clicked with me yet, so this may sound like a too easy question. In my homework, I need to: Create a single instance of the class in function main().
What does my professor mean by that? When I tried searching for an answer, they were too specific to a problem, and I just want a general answer please
Sound like you just need something like:
class A {};
int main() {
A a; // creates instance of class A
return 0;
}
Below is my codeļ¼š
Singleton.h
#ifndef __C__Review__Singleton__
#define __C__Review__Singleton__
#include <iostream>
class Singleton{
private:
Singleton() { }
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
static Singleton *instance;
public:
static Singleton *getInstance();
static void release();
};
#endif /* defined(__C__Review__Singleton__) */
Singleton.cpp
#include "Singleton.h"
Singleton *Singleton::instance = 0;
Singleton* Singleton::getInstance()
{
if(instance == nullptr)
instance = new Singleton();
return instance;
}
void Singleton::release()
{
if (instance != NULL) {
delete instance;
instance = NULL;
}
}
Classes are one of the main part of C++. Moreover, using OOPs concepts while creating and extending classes is also very powerful feature of cpp.
Classes contains properties and member functions. Both of these can be public, private or protected.
Private members of a class are accessible only from within other member functions of the same class.
Protected are similar to private but, they can be accessed by child classes also.
Public members, as the name suggests, can be accessed by objects(instance) of the class.
You can visualize class as a type and object as a variable if that type. Just for understanding.
Classes in C++ are created as follows.
class Circle {
int radius; // member variable/property
public: // type of function()
void set_values (int,int);
int area() {return 3.14*radius*radius;}
};
Creating an object/instance of class means you are creating a variable of type class.
Objects can simply be crated as follows:
Circle c; // Stack based object
static Circle t1; // Static object
Here, keyword static is used to create a singleton instance/object of that class.
For further information, just google it. May be basic knowledge of C++ is required, can be obtained from this,this or this links.

Persisting global data that needs initialising in C++

I have a global user defined type "foo"in a dll that is responible for the creation and deletion of a reference counted HINSTANCE. Problem is it needs to be initialised with a string by a function called on the dll.
What is my best option for doing this? How can a function create a "foo" that will be global and persist with a valid HINSTANCE over multiple function calls. Thanks
You can use a singleton:
class CFoo
{
public:
static CFoo* m_instance;
static CFoo* GetInstance()
{
if(!m_instance)
{
m_instance = new CFoo();
}
return m_instance;
}
private:
CFoo();
};