I have the below CPP source code for creating a Singleton Object of a class using unique_ptr:
#include <iostream>
#include <memory>
class A
{
public:
std::unique_ptr<A> getInstance(int log);
~A();
private:
static bool instanceFlag;
static std::unique_ptr<A> single;
A(int log);
int mLog;
};
bool A::instanceFlag = false;
std::unique_ptr<A> A::single = NULL;
std::unique_ptr<A> A::getInstance(int log)
{
if(!instanceFlag)
{
//single = std::make_unique<A>(log);
single = std::unique_ptr<A>(new A(log));
instanceFlag = true;
return std::move(single);
}
else
{
return std::move(single);
}
}
A::A(int log) :
mLog(log)
{
std::cout << "Called A cons" << std::flush << std::endl;
}
int main()
{
std::unique_ptr<A> mA = A::getInstance(5);
}
But when I compile the code I get below error:
$ c++ -std=c++11 try2.cpp
try2.cpp: In function 'int main()':
try2.cpp:45:41: error: cannot call member function 'std::unique_ptr<A> A::getInstance(int)' without object
std::unique_ptr<A> mA = A::getInstance(5);
^
However I have exactly the same format of code in my project I get an error :
Source code Line 39: single = std::make_unique<A>(log);
Compilation error:
39: required from here
single = std::make_unique<A>(log);
error: A(int log)' is private
A::A(int log) :
^
First, the static issue. This:
std::unique_ptr<A> getInstance(int log);
is an instance method. You need an instance of A to call it on, but you can't get an instance of A without calling this method first, so ...
The reason for using instance methods is that they have access to the instance they're invoked on. Your method only uses the following members:
static bool instanceFlag;
static std::unique_ptr<A> single;
which, since they're static, don't need an instance. Just make the method static too, and you'll be able to call it without first getting an A from somewhere.
Second, the logic issue. Your getInstance method returns a unique_ptr to your single instance. The entire point of unique_ptr is that's it's unique: exactly one pointer owns and controls the lifetime of an object. When you returned a unique_ptr, you transferred ownership of the singleton object from the singleton class itself, to the caller. You even explicitly called move to make it really clear that this is happening.
Now, after calling getInstance once, your singleton is completely broken. If you call getInstance again, the singleton believes it has an instance (because instanceFlag), but the unique_ptr is in an indeterminate state. The only thing we can say for sure is that it doesn't control an instance of A.
Just return a raw pointer (or reference) to A instead of transferring ownership.
Short answer: Don't use singletons.
Long answer: std::make_unique() uses constructor of an object it tries to create, and in your code it's private. Since it is an external function, it's not possible. You can create an object on your own and pass it to std::unique_ptr to manage, like you do on the line below the commented one.
The most important problem is, when you do std::move(), your class member single is gone. It becomes empty unique_ptr (aka. std::unique_ptr{}, it doesn't manage anything). With any next call to getInstance, you're essentially returning nullptr. You should use std::shared_ptr, which you'll want to return by copy or return reference to your std::unique_ptr.
Even after making the getInstance static, it won't compile because the definition for destructor is missing. Either give empty definition or leave it as default.
~A() = default;
Moving single will work first time and invokes UB for subsequent calls to getInstance. Instead return by reference & and remove std::move
static std::unique_ptr<A>& getInstance(int log);
std::unique_ptr<A>& A::getInstance(int log)
{
if(!instanceFlag)
{
//single = std::make_unique<A>(log);
single = std::unique_ptr<A>(new A(log));
instanceFlag = true;
return single;
}
else
{
return single;
}
}
Inside main() you can get by reference
std::unique_ptr<A>& mA = A::getInstance(5);
The problem is that, as error log suggests, you are calling member function i.e. getInstance without any instance. Function std::unique_ptr<A> getInstance(int log); should be declared as static.
Declare it static as follow:
static std::unique_ptr<A> getInstance(int log);
Note: In singleton pattern getInstance function is always static function.
Following is an extract from Wikipedia:
An implementation of the singleton pattern must:
ensure that only one instance of the singleton class ever exists; and
provide global access to that instance.
Typically, this is done by:
declaring all constructors of the class to be private; and
providing a static method that returns a reference to the instance.
The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called.
Related
And again a bad-formulted question, but I don't know how to shortly explain this situation:
I have two classes. Let's name them A and B. A has a lot of member variables and methods. B is a struct which has a shared_pointer to an object of type A. Now A has a method that returns an instance of B (with a pointer to the current instance of A).
My problem is, that A is the subclass of C. C has the same method as described above as pure virtual. The code would look like this:
class C {
public:
virtual B mymethod() const =0;
virtual int getMyvar() const =0;
};
class A : public C {
public:
B mymethod() const override;
int getMyvar() const override; //outputs myvar
private:
int myvar;
};
struct B {
std::shared_ptr<C> pointer;
};
B A::mymethod() const {
B instance;
instance.pointer = std::make_shared<A>(*this); //is this wrong?
return instance;
}
My compiler (gcc 4.8.2) creates the executables for the following code, but at runtime I get "Segmentation fault (core dumped)":
void AnotherClass::something() const {
A object;
B instance = object.mymethod();
std::cout << instance.pointer->getMyvar(); //dumps the core womehow?
}
I read about the std::enable_shared_from_this but I could not figure out how it works or if it helps me.
Why do I get the error message and how can I fix this?
From what I have read in the manual, you do:
class A : public C, std::enable_shared_from_this<A> {
public:
B mymethod() override; // Notice the lack of const
private:
int myvar;
};
and then:
B A::mymethod() {
B instance;
instance.pointer = shared_from_this(); // this should be right
return instance;
}
Like this, all the instances of a std::shared_ptr to the same A object will share the same reference counter, and it will be destroyed only when it must be.
EDIT:
Also, notice that your object A must be managed by some other std::shared_ptr before you can call A::mymethod(). I.e. you must create A objects like this:
std::shared_ptr<A> a_obj(new A);
then you can call A::mymethod():
B b_obj = a_obj->mymethod();
EDIT2:
Method A::mymethod() (and consequently, C::mymethod()) can't be const to be able to call the non-const method shared_from_this().
Preliminary problem: how do you down-cast to access myvar ?
Edit: after your edit, this first topic is no longer relevant. I leave it because I used this code in the live demos illustrating how to solve it.
First, the statement that causes the dump can't compile as you gave it:
std::cout << instance.pointer->myvar;
because instance.pointer is a shared_ptr<C> and C has no member myvar.
If downcasting properly with dynamic_pointer_cast<A>(instance.pointer)->myvar (supposing AnotherClass is a friend) it works.
Your shared pointer made a clone: is it your intent ?
This statement:
instance.pointer = std::make_shared<A>(*this); //is this wrong? PERHAP'S !?
creates a clone object obtained by copy construction from *this. So you don't reference the original object A, and hence you don't need std::enable_shared_from_this : the use count of instance.pointer will be 1 because at that moment there's only one reference to the newly created shared object.
Live demo
Or do you want it to reference the original object ?
You then have to change the statement to:
instance.pointer = std::shared_ptr<A>(this); //better ?
But this won't compile because mymethod() is const, so it consider this as being a pointer to const. To compile the statement you must either remove the constness of mymethod() or add constness to B's pointer.
Then it works. B's shared pointer has still a use count of 1, which is again ok. But once this shared_ptr gets out of scope, the use count is 0 and the shared_ptr's destructor will try to delete the object. AS IT WAS INITIALY A LOCAL OBJECT (ON STACK) this causes a runtime error.
Final approach
As you want to have shared pointers to your object, the code of AnotherClass should be something like:
shared_ptr<C> pobject(new A); // create the object from the free store
B instance = pobject->mymethod();
...
And the C class must inherit as follows:
class C : public std::enable_shared_from_this<C>
{...}
And the my method class must initialize the shared_pointer it retures as follows:
//instance.pointer = std::shared_ptr<A>(this); // no, don't do no longer !!
instance.pointer = shared_from_this(); //<===== RETURN A POINTER TO SELF
Then everything works perfectly.
Live demo
It seems to me that you would get a memory error when your objects go out of scope.
When you create your object A and then create your shared_ptr with the this pointer, your counter will be 1 instead of 2 (as you would maybe expect). So A will be destroyed twice, instead of once.
A more correct way of doing this would be create class A as a shared_ptr and initialize the pointer in class B with it (not inside class A). This way the counter will be incremented as you expect and A will be deleted only once.
The class you want to share will need to inherit from enable_share_from_this.
Then you can call share_from_this to obtain a shared pointer to the class you're in.
If you just try and make_shared you just create a separate ownership group that will mean two things will try and delete your object. That will be the cause of your segfault.
I'm browsing some random code and I found some confusing method, the class is a singleton,
class CFoo
{
CFoo* _instance;
CFoo(){};
public:
~CFoo(){};
static CFoo* getInstance()
{
if(!_instance)
_instance = new CFoo;
return _instance;
}
static void deleteInstance()
{
if(_instance)
delete _instance;
}
// just ordinary member method.
void FooMethod()
{
CFoo::getInstance()->BarMethod(); //confusing..
}
// just ordinary member method.
void BarMethod()
{
//code here..
}
};
CFoo* CFoo::_instance = NULL;
Why FooMethod have to call the CFoo::getInstance() to call the BarMethod? Why not just calling BarMethod() directly?
Please advise.
If you call CFoo::getInstance()->BarMethod() within CFoo::FooMethod(), then the this keyword in the BarMethod refers to CFoo::_instance.
If you call BarMethod() within CFoo::FooMethod(), then the this keyword in the BarMethod refers to the same object on which FooMethod() was called.
It is not entirely clear whether there is effectively any difference. On the one hand, the only constructor that you implemented is private and you refer to the class as a Singleton. This supports the fact that only one instance of CFoo should exist, i.e. this == CFoo::_instance should always hold within BarMethod. On the other hand, CFoo has a public copy constructor, so this == CFoo::_instance might not always be true within BarMethod.
You could call the FooMethod and the Barmethod directly if you could create an object of this class. the problem is you can't do it because the construtor is private. the only way you can create the instance is using the getInstance method. and the method ensure it had no more than single object of this class.
That's why it called singleton.
I was wondering if (in C++) you can instantiate a class (class foo) then have said class return the already instantiated object. (foo::instance())
In other words, can I have a class return it's-self via it's own methods? I want to be able to create a class (i.e. class foo) early in my program so it is already setup and ready to go. Then, farther down the line, I want to be able to call functions from that class without having to pass that object as an argument to my calling function. Can I do something like so:
MyClass::ReturnSelf()->foo();
or
MyClass::ReturnSelf().foo();
EDIT: I just realized this might be a little unclear. I want to be able to have another class call this "self-returning" method so it can use the already instantiated object's methods and members without creating a new object.
Congrats, you've discovered the singleton pattern. Quite a caveat, if you didn't already know it.
struct X
{
static X& instance()
{
static X x;
return x;
}
void foo();
};
and call the method as:
X::instance().foo();
Of course, you could also make the method static, if that's an option, and call it directly:
X::foo(); //this requires foo to be declared static
The effect of returning the instance from methods can also be used for method chaining:
struct Element
{
Element& setColor() { return *this; }
Element& setWidth() { return *this; }
};
Element e;
e.setColor().setWidth();
A static member function usually does the trick:
struct Foo
{
static Foo & special_instance()
{
static Foo impl; // Alarm bells: This is a global state!
return impl;
}
// ...
};
Usage (from anywhere in the code):
Foo & f = Foo::special_instance();
// ...
You have the additional option of making all the constructors of the class private so that this sort of object creation is the only option. This is generally awkward design, but there may be situations where it is useful. Just be mindful whether you're modeling your problem correctly or whether you might get away with something simpler.
I just realized this might be a little unclear. I want to be able to have another class call this "self-returning" method so it can use the already instantiated object's methods and members without creating a new object.
define a class-variable in class foo of type foo that you can return in static class method instance(). You may also try to give it type *foo and set it up with a pointer on first ctor, wich makes it possible to derive from your class.
class Foo
{
# class variable pointing to first instance
static foo* pFoo = null;
# constructor, sets pointer to first instance
Foo()
{
if (!pFoo) pFoo = this;
/* ... */
}
# static class method returning instance
static foo* instance() {return pFoo;}
}
I'm experiencing a weird issue in which I need to have a default constructor for my template class to work, but some of the classes I'd like to use with the template cannot have default constructors.
What I mean by some classes cannot have default constructors is they have a const reference field, hence, they must be set in the constructor/initialization list. If I have a default constructor, there is nothing to set these references to.
So, I guess there are two possible solutions to this: Find a way to allow for non-default constructors in the template class sometimes or find a way to set the const reference fields in a default constructor.
How do I resolve this?
Here's my template code:
#pragma once
template<class T>
class Singleton
{
public:
static T* getInstance()
{
if(!instance) instance = new T;
return instance;
}
static void setInstance(T* inst)
{
instance = inst;
}
protected:
Singleton();
~Singleton();
private:
Singleton(Singleton const&);
Singleton& operator=(Singleton const&);
static T* instance;
};
template<class T> T* Singleton<T>::instance = 0;
Here's where I set the const reference (in a .cpp):
InputHandler::InputHandler(const sf::Input& inputObject)
: input(inputObject)
{
And input is defined in the header:
const sf::Input& input;
I have to use a constant reference because of this area of code (in a different file):
const sf::Input& input = window.GetInput();
InputHandler* inputHandler = new InputHandler(input);
Singleton<InputHandler>::setInstance(inputHandler);
GetInput() is not one of my methods, and it must return a const sf::Input&
You're invoking the default constructor in getInstance with:
instance = new T;
What do you expect to happen if someone calls getInstance before setInstance?
If it's an error to call getInstance before setInstance, then getInstance should assert or throw or return NULL if called before instance is set. Just get rid of the new T, and your code will compile.
If it's not an error to call getInstance before setInstance, then you don't really have a singleton. Early callers would receive a default constructed object and later callers would get the one set later. That's two instances and therefore not a singleton.
If you have a reference member, then you cannot (sensibly) make your class default-constructible or assignable, since references must be initialised, and can't be reassigned.
If you need those properties from the class, then you probably want the member to be a pointer, initialised to null by default and assignable later if needed.
You could perhaps have the Singleton constructor set the instance pointer, i.e.
Singleton::Singleton()
{
assert(instance == nullptr);
instance = static_cast<T*>(this);
}
You can then remove the setInstance function from the interface and getInstance can simply return instance.
In response to the comment, I was assuming that classes were being defined like this:
class MyClassThatShouldBeASingleton : public Singleton<MyClassThatShouldBeASingleton>
{
};
Of course, this does mean that you need to explicitly set up such a singleton rather than it instantiating automatically as in the original code. It's not necessarily how you'd want all singletons to work, just one way of solving the problem.
I've been looking at the example C++ Factory method pattern at Wikipedia and have a couple of questions:
Since the factory method is static, does that mean the newly created object won't go out of scope and have the destructor method called when the factory method exits?
Why return a pointer, as opposed to a reference? Is it strictly a matter of preference, or is the some important reason for this?
Edit 1: The more I think about it, both the reference and the pointer returned will stay in scope because they are referenced outside of the method. Therefore, the destructor won't be called on either one. So it's a matter of preference. No?
Edit 2: I printed out the destructor call on the returned reference, and it doesn't print until the program exits. So, barring further feedback, I'm going to go with the reference for now. Just so I can use the "." operator on the returned object.
Static method is one that can be called without having an instance of the factory. That has nothing to deal wtih the lifetime of the newly created object. You could use a non-static method with the same success. The factory method usually doesn't need any data from an existing object of the same class and therefor doesn't need an existing instance and this is why factorey methods are usually static.
You will use new to create the object that the factory will return. It's usual to return them by pointer. This shows explicitly that it's a new object ant the caller must take care of its lifetime.
I'm thinking there is a greater issue of understanding memory management. The factory method is allocating items on the heap (using new). Items on the heap never get automatically reclaimed (except by modern desktop OSs on process termination). The behavior you are describing is for items on the stack where they are reclaimed when you leave the local scope.
If you return a reference to an object that reference will become invalid when the method goes out of scope. This won't happen with a pointer, since the destructor isn't called.
It is true that static modifies when the value goes out of scope, but only if the variable is declared static, not if the method is declared static.
Your Wiki link says wrong.
There shouldn't be any static method. You can consider Factory Method as Template Method pattern that creates Objects. This method doesn't receive any "Name" parameter and create all the time same type of object.
Often, designs start out using Factory
Method (less complicated, more
customizable, subclasses proliferate)
and evolve toward Abstract Factory,
Prototype, or Builder (more flexible,
more complex) as the designer
discovers where more flexibility is
needed. [GoF, p136]
In the following example Business::makeObject is the factory method
class ObjectBase
{
public:
virtual void action() = 0;
virtual ~ObjectBase(){};
};
class ObjectFirst : public ObjectBase
{
public:
virtual void action(){ std::cout << "First"; }
};
class ObjectSecond : public ObjectBase
{
public:
virtual void action(){ std::cout << "Second"; }
};
class Business
{
public:
void SendReport()
{
std::auto_ptr< ObjectBase > object(makeObject());
object->action();
}
virtual ~Business() { }
protected:
virtual ObjectBase* makeObject() = 0;
};
class BusinessOne: public Business
{
public:
protected:
virtual ObjectBase* makeObject()
{
return new ObjectFirst();
}
};
class BusinessTwo: public Business
{
public:
protected:
virtual ObjectBase* makeObject()
{
return new ObjectSecond();
}
};
int main()
{
std::auto_ptr<Business> business( new BusinessTwo() );
business->SendReport();
return 0;
}
No. Static method - is almost same as global function in class namesapce and with access to private static variables;
Pointers usage is issue of createing objects in heap. They create object in heap for longer object lifetime than create-function scope;
EDIT:
I think wikipedia - is wrong in c++ example.
We have in exmaple - not same implementation as in class diagram or here (http://www.apwebco.com/gofpatterns/creational/FactoryMethod.html)
It will be better if you read about patterns from most trusted sources, e.g: Design Patterns: Elements of Reusable Object-Oriented Software.
The keyword static means different things on a method and on a variable. On a method as in the example it means that it is class global, and you need not have an instance of the class to call it.
To create a new object dynamically you need to use new, or 'a trick' is to assign a temporary object to a reference. assigning a temporary object to a point will not keep that object alive.
So you could do the following, but it is not normally done because you would often want to keep many things created from a factory, and then you would have to copy them rather than simply holding the pointer in a list.
class PizzaFactory {
public:
static Pizza& create_pizza(const std::string& type) {
if (type == "Ham and Mushroom")
return HamAndMushroomPizza();
else if (type == "Hawaiian")
return HawaiianPizza();
else
return DeluxePizza();
}
};
const Pizza &one = create_pizza(""); // by ref
Pizza two = create_pizza(""); // copied
EDIT
Sorry mistake in code - added missing const to ref.
Normally, a temporary object lasts only until the end of the full expression in which it appears. However, C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself