How to convert a singleton in c# to c++? - c++

I have this c# code:
class Animacion
{
private static Animacion instancia;
public static Animacion Instance
{
get
{
if (instancia == null)
{
instancia = new Animacion();
}
return instancia;
}
}
I want to convert that code to c++, I tryed to use a code converter from tangible software solutions and I got this:
//.h file code:
class Animacion
{
private:
static Animacion *instancia;
public:
static Animacion *getInstance() const;
};
//.cpp file code:
Animacion *Animacion::getInstance() const
{
if (instancia == nullptr)
{
instancia = new Animacion();
}
return instancia;
}
When I use the code generated from the converter I get errors like:
error: C2272: 'getInstance' : modifiers not allowed on static member functions
can anyone help me?

static Animacion *getInstance() const; get rid of the const. There's no point making a static class member function const in c++, hence the compiler error.
Also the established idiom for singletons in c++ looks rather like:
class Animacion {
private:
Animacion() {}
Animacion(const Animacion&) = delete;
Animacion& operator=(const Animacion&) = delete;
public:
static Animacion& getInstance() {
static Animacion theInstance;
return theInstance;
}
};
Further you should note, that Singleton is a really questionable design pattern, and you likely could live without it, in preference of an injected interface for the clients. That would help in decoupling implementation, from usage.

Related

Access base class variable from child static function

class A
{
public:
void init();
void method1();
void method2();
private:
bool _var1 = false;
bool _var2 = false;
};
class B : public A
{
public:
static void method3();
};
B::method3()
{
_var1 = false
}
If I call method3, I get the expected error "invalid use of member 'A::_var1' in static member function".
I have many classes which need to be static (have static functions), and many of the common variables and properties I need to inherit from a base class for code tidiness. What's the best solution for this problem?
Point me in the right direction, thank you.
a static function is not associated with an object hence cannot access class members.
see reference for more details.
you may need to pass an object instance as a function argument if that static function requires to use one e.g.
B::method3(B& b)
{
// do something with b
if b.isConnected() ) {}
}
bool B::isConnected(){return _isconnected;}

iOS: calling C++ singleton using Objective-C

I have C++ singleton implementation like this:
#include "DoingSomething.hpp"
class DoingSomething
{
static DoingSomething *shareInstance;
public:
int doSomething()
{
/*
*/
return someValue;
}
static DoingSomething *instance()
{
if (!shareInstance)
shareInstance = new DoingSomething;
return shareInstance;
}
};
But I want to access the singleton and the public functions inside of the singleton on my viewController using Objective-C. Any of you knows how can this be done?
I'll really appreciate your help.

C++ getting access to SingleTune class member methods getting Member access into incomplete type

i have simple singleton that holds another class as its member
i try to access this member class public methods and i get :
Member access into incomplete type
my singleton class :
#include "SoundManager.h"
class Singleton : pSoundManager(new SoundManager())
{
public:
static
Singleton getInstance()
{
if (!instance_)
{
instance_ = new Singleton();
}
return instance_;
}
SoundManager* getSoundManager( return pSoundManager;);
private:
static Singleton* instance_;
Singleton() {};
~Singleton(){};
SoundManager* pSoundManager;
}
//the class that kept in the singleton
class SoundManager
{
public:
SoundManager(){};
~SoundManager(){};
unsigned int playEffect() {printf("effect!!");};
private:
};
and now when i try to do
Singleton::getInstance()->getSoundManager()->playEffect() ;
im getting :
Member access into incomplete type 'SoundManager'
what im doing wrong here?
This code
SoundManager* getSoundManager( return pSoundManager;);
is syntactically wrong in a way the error messages you see could get misleading. Replace this code with
SoundManager* getSoundManager() { return pSoundManager; }
What I would do is, simplifying the getInstance() function a bit (besides fixing some of the obvious syntactic errors):
#include "SoundManager.h"
class Singleton {
public:
static
Singleton& getInstance() {
static Singleton instance_;
return instance_;
}
SoundManager& getSoundManager() { return soundManager_; }
private:
Singleton() {};
~Singleton(){};
SoundManager soundManager_;
};
Calling the playEffect() function would change to
Singleton::getInstance().getSoundManager().playEffect();
accordingly of course.
The
class Singleton : pSoundManager(new SoundManager())
is not valid C++ construction. The g++ compiler cannot eat it. You should move it into the constructor. Probably it is an issue.
Additionally, you should explicitly initialize the instance_ member to the NULL value because the C++ standard says that the not-initialized members contain unpredicted values. So, the
if (!instance_)
condition can be false without first initialization.

Using a Static Class function to create a Singleton object/instance

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.

Cannot access private member in singleton class destructor

I'm trying to implement this singleton class. But I encountered this error:
'Singleton::~Singleton': cannot access private member declared in class 'Singleton'
This is flagged in the header file, the last line which contains the closing brace.
Can somebody help me explain what is causing this problem?
Below is my source code.
Singleton.h:
class Singleton
{
public:
static Singleton* Instance()
{
if( !pInstance )
{
if( destroyed )
{
// throw exception
}
else
{
Create();
}
}
return pInstance;
}
private:
static void Create()
{
static Singleton myInstance;
pInstance = &myInstance;
}
Singleton() {}
Singleton( const Singleton& );
Singleton& operator=( const Singleton& );
~Singleton()
{
pInstance = 0;
detroyed = false;
}
static Singleton* pInstance;
static bool destroyed;
};
Singleton.cpp:
Singleton* Singleton::pInstance = 0;
bool Singleton::destroyed = false;
Inside my main function:
Singleton* s = Singleton::Instance();
If I make the destructor as public, then the problem disappears. But a book (Modern C++ Design) says it should be private to prevent users from deleting the instance. I actually need to put some code for cleanup for pInstance and destroyed inside the destructor.
By the way, I'm using Visual C++ 6.0 to compile.
You should probably have let us know that the version of Visual C++ you're working with is VC6. I can repro the error with that.
At this point, I have no suggestion other than to move up to a newer version of MSVC if possible (VC 2008 is available at no cost in the Express edition).
Just a couple other data points - VC2003 and later have no problem with the Singleton destructor being private as in your sample.
The code you posted looks doesn't have any problem, so the problem must be in some other part of your source code.
The error message will be preceded by the filename and line number where the problem is occurring. Please look at the line and you'll see a bit of code that is either trying to call delete on a singleton pointer or is trying to construct an instance of singleton.
The error message will look something like this (the file and line number are just an example):
c:\path\to\file.cpp(41) : error C2248: 'Singleton::~Singleton': cannot access private member declared in class 'Singleton'
So in that case, you would want to see what is happening at line 41 in file.cpp.
I'm no C++ or VC expert, but your example looks similar to the one described on this page ... which the author calls a compiler bug.
Personally i haven't put destructors in my singletons unless i am using a template singleton class, but then i make them protected.
template<class T>
class Singleton
{
public:
static T &GetInstance( void )
{
static T obj;
return obj;
}
static T *GetInstancePtr( void )
{
return &(GetInstance());
}
protected:
virtual ~Singleton(){};
Singleton(){};
};
then write my class as
class LogWriter : public Singleton<LogWriter>
{
friend class Singleton<LogWriter>;
}
class Singleton
{
static Singleton *pInstance = NULL;
Singleton(){};
public:
static Singleton * GetInstance() {
if(!pInstance)
{
pInstance = new Singleton();
}
return pInstance;
}
static void RemoveInstance() {
if(pInstance)
{
delete pInstance;
pInstance = NULL;
}
}
};