Factory method pattern implementation in C++: scoping, and pointer versus reference - c++

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

Related

Return a shared_ptr from a class C++

I have a question which has to do with returning a shared pointer from a class.
Part of my class looks like this:
typedef std::shared_ptr<IBaseInterface> IBaseInterfaceSP;
...
IBaseInterfaceSP getMyInterface()
{
m_spBase = std::make_shared<IBaseInterfaceSP>( m_derivedInterface);
return m_spBase;
}
where both m_derivedInterface and m_spBase are private members of my class, i.e:
private:
IBaseInterfaceSP m_spBase ;
DerivedInterface m_derivedInterface;
Also, DerivedInterface inherits from IBaseInterfaceSP.
getInterface is a public function of my class.
Is this the right way to return a pointer from my class? Will there be any problems with slicing or anything similar?
P.S. I am sorry if something is unclear ( I am not allowed to post all the code here in public, only some parts), if so, just let me know.
I can see several problems with this code.
1. Lazy initialization
Each time you call getInterface, you create a new instance of your IBaseInterface class. As a user of your class, I would not expect this behavior from a method called "get".
I guess you wanted to implement lazy initialization, in which case you would do it like this:
IBaseInterfaceSP getInterface()
{
if (!m_spBase)
{
m_spBase= std::make_shared<IBaseInterface>( m_derivedInterface );
}
return m_spBase;
}
2. Naming conventions
You are instantiating a class called IBaseInterface, which sounds like an abstract class (the "I" prefix was historically used for interfaces). You should probably rename your class so that it doesn't sound abstract. Also, the "I" prefix is redundant with the "Interface" suffix.
However, in what I consider "good" OOP, users do not need to know that you are handing them an interface. There is thus no need for a naming convention that differentiates concrete from abstract classes.
3. Ownership semantics
Shared pointers are meant for shared ownership: when you return a shared pointer, you are telling the users of your class that they will own the returned object, too. Usually, that is not needed. In most cases you would return a non-owning pointer, a.k.a. raw pointer. For example:
IBaseInterface* getInterface()
{
return m_spBase.get(); // Instantiation done elsewhere, for example in constructor
}
4. Slicing
There is indeed slicing happening here. This line:
m_spBase = std::make_shared<IBaseInterface>( m_derivedInterface );
Actually expands to code that contains something equivalent to this:
auto newInstance = new IBaseInterface(m_derivedInterface );
In turn, the line above will call the copy constructor of the IBaseInterface class, whose signature is similar to:
IBaseInterface(IBaseInterface& other)
Thus, m_derivedInterface is interpreted as an IBaseInterface reference in the context of that call. Only the members of IBaseInterface will thus be copied during the call to "new", thereby losing all the information stored in the derived class, DerivedInterface.
All that said, it seems to me that what you really want is direct access to the m_derivedInterface object. What you are doing right now is, you copy the instance into another object and return the new object. I think what you really want is this:
IBaseInterface* getInterface()
{
return &m_derivedInterface;
}
If you insist on using shared ownership, just store a shared pointer to m_derivedInterface instead of a value:
MyClass(Args args)
{
m_derivedInterface.reset(new DerivedInterface(args));
}
std::shared_ptr<IBaseInterface> getInterface()
{
return m_derivedInterface;
}
std::shared_ptr<IBaseInterface> m_derivedInterface;

Use of public destructor when the constructor is private

I have seen code where the constructor has been declared as private while the destructor is public. What is the use of such a declaration? Is the destructor required to be public so that during inheritance the calls can be possible or is it a bug in the code?
The question might seem to be a bit short on information, but what I really want to know is if having a public destructor when the constructor is required to be private abides by the C++ rules?
Short Answer
Creating a constructor as private but the destructor as public has many practical uses.
You can use this paradigm to:
Enforcing reference counting (See Hitesh Vaghani's example).
Implement the singleton pattern
Implement the factory pattern.
Long Answer
Above I hinted that you can use private constructors and destructors to implement several design patterns. Well, here's how...
Reference Counting
Using private destructor within an object lends itself to a reference counting system. This lets the developer have stronger control of an objects lifetime.
class MyReferenceObject
{
public:
static MyReferenceObject* Create()
{
return new MyReferenceObject();
}
void retain()
{
m_ref_count++;
}
void release()
{
m_ref_count--;
if (m_ref_count <= 0)
{
// Perform any resource/sub object cleanup.
// Delete myself.
delete this; // Dangerous example but demonstrates the principle.
}
}
private:
int m_ref_count;
MyReferenceObject()
{
m_ref_count = 1;
}
~MyReferenceObject() { }
}
int main()
{
new MyReferenceObject(); // Illegal.
MyReferenceObject object; // Illegal, cannot be made on stack as destructor is private.
MyReferenceObject* object = MyReferenceObject::Create(); // Creates a new instance of 'MyReferenceObject' with reference count.
object->retain(); // Reference count of 2.
object->release(); // Reference count of 1.
object->release(); // Reference count of 0, object deletes itself from the heap.
}
This demonstrates how an object can manage itself and prevent developers from corrupting the memory system. Note that this is a dangerous example as MyReferenceObject deletes itself, see here for a list of things to consider when doing this.
Singleton
A major advantage to private constructors and destructors within a singleton class is that enforces the user to use it in only the manner that the code was design. A rogue singleton object can't be created (because it's enforced at compile time) and the user can't delete the singleton instance (again, enforced at compile time).
For example:
class MySingleton
{
public:
MySingleton* Instance()
{
static MySingleton* instance = NULL;
if (!instance)
{
instance = new MySingleton();
}
return instance;
}
private:
MySingleton() { }
~MySingleton() { }
}
int main()
{
new MySingleton(); // Illegal
delete MySingleton::Instance(); // Illegal.
}
See how it is almost impossible for the code to be misused. The proper use of the MySingleton is enforce at compile time, thus ensuring that developers must use MySingleton as intended.
Factory
Using private constructors within the factory design pattern is an important mechanism to enforce the use of only the factory to create objects.
For example:
class MyFactoryObject
{
public:
protected:
friend class MyFactory; // Allows the object factory to create instances of MyFactoryObject
MyFactoryObject() {} // Can only be created by itself or a friend class (MyFactory).
}
class MyFactory
{
public:
static MyFactoryObject* MakeObject()
{
// You can perform any MyFactoryObject specific initialisation here and it will carry through to wherever the factory method is invoked.
return new MyFactoryObject();
}
}
int main()
{
new MyFactoryObject(); // Illegal.
MyFactory::MakeObject(); // Legal, enforces the developer to make MyFactoryObject only through MyFactory.
}
This is powerful as it hides the creation of MyFactoryObject from the developer. You can use the factory method to perform any initilisation for MyFactoryObject (eg: setting a GUID, registering into a DB) and anywhere the factory method is used, that initilisation code will also take place.
Summary
This is just a few examples of how you can use private constructors and destructors to enforce the correct use of your API. If you want to get tricky, you can combine all these design patterns as well ;)
First thing: the destructor can be private.
having a public destructor when the constructor is required to be
private abides by the C++ rules?
It's totally working in C++. In fact, a great example of this scenario is the singleton pattern, where the constructor is private and the destructor is public.
In reverse order.
Is the destructor required to be public so that during inheritance the calls can be possible or is it a bug in the code?
Actually, for inheritance to work the destructor should be at least protected. If you inherit from a class with a private destructor, then no destructor can be generated for the derived class, which actually prevents instantiation (you can still use static methods and attributes).
What is the use of such declaration?
Note that even though the constructor is private, without further indication the class has a (default generated) public copy constructor and copy assignment operator. This pattern occurs frequently with:
the named constructor idiom
a factory
Example of named constructor idiom:
class Angle {
public:
static Angle FromDegrees(double d);
static Angle FromRadian(double d);
private:
Angle(double x): _value(x) {}
double _value;
};
Because it is ambiguous whether x should be precised in degrees or radians (or whatever), the constructor is made private and named method are provided. This way, usage makes units obvious:
Angle a = Angle::FromDegrees(360);
You make constructor private if you want to prevent creating more then one instance of your class. That way you control the creation of intances not their destruction. Thus, the destructor may be public.
One example in my head, let's say you want to limit the class instance number to be 0 or 1.
For example, for some singleton class, you want the application can temprary destroy the object to rducue memory usage. to implement this constructor will be private, but destructor will be public. see following code snippet.
class SingletoneBigMemoryConsumer
{
private:
SingletoneBigMemoryConsumer()
{
// Allocate a lot of resource here.
}
public:
static SingletoneBigMemoryConsumer* getInstance()
{
if (instance != NULL)
return instance;
else
return new SingletoneBigMemoryConsumer();
}
~SingletoneBigMemoryConsumer()
{
// release the allocated resource.
instance = NULL;
}
private:
// data memeber.
static SingletoneBigMemoryConsumer* instance;
}
//Usage.
SingletoneBigMemoryConsumer* obj = SingletoneBigMemoryConsumer::getInstance();
// You cannot create more SingletoneBigMemoryConsumer here.
// After 1 seconds usage, delete it to reduce memory usage.
delete obj;
// You can create an new one when needed later
The owner of an object needs access to the destructor to destroy it. If the constuctors are private, there must be some accessible function to create an object. If that function transferes the ownership of the constructed object to the caller ( for example return a pointer to a object on the free store ) the caller must have the right to access the destructor when he decides to delete the object.

C++: An abstract class as a member

I have a question about style. I have a class (in my case an Option) that depends on the value of an exogenous object (Interest Rate). My goal is to create a abstract base class for the exogenous object (Rate) so that I can construct variations, say SimulatedRate or ConstantRate, that will work inside my depending class, Option.
However, I'm finding in C++, since I obviously cannot instantiate a abstract base class, I must store either a pointer or a reference to the base class. My concern is that when the instantiated exogenous objects go out of scope outside of the dependent class, my dependent class will be pointing to junk.
Is there a reasonable way to utilize polymorphism for this problem in C++?
My current code:
class Dependent
{
public:
Dependent(const Exogenous& exo) : exo_(exo) {}
double getSomething() const { exo_.interfaceMethod(); }
private:
Exogenous& exo_;
}
class Exogenous
{
public:
virtual double interfaceMethod() const=0;
}
class ExogenousVariationA
{
public:
virtual double interfaceMethod() const { return resultA; }
}
class ExogenousVariationB
{
public:
virtual double interfaceMethod() const { return resultB; }
}
Your worry is valid. Since you are storing to a reference an object passed in by the client, you are trusting that client to keep the object alive while you need it. This can easily lead to problems. Of course, the same would be true if you used raw pointers to dynamically allocated objects. If the client does delete on the object before you're done with it, once again you have a problem.
The solution is to force the client to give you some kind of responsibility over the lifetime of the object. The way to do this is to ask for a smart pointer. Depending on your problem, you may want a std::unique_ptr or std::shared_ptr. Use the former if you want to take ownership from the client or the latter if you want to share ownership with them. Let's say you choose std::unique_ptr, you would then define your Dependent class as:
class Dependent
{
public:
Dependent(std::unique_ptr<Exogenous> exo) : exo_(std::move(exo)) {}
double getSomething() const { exo_->interfaceMethod(); }
private:
std::unique_ptr<Exogenous> exo_;
}
The client would use this like so:
std::unique_ptr<Exogenous> ptr(new ExogenousVariationA());
Dependent dep(std::move(ptr));
Now, when your client passes the std::unique_ptr to you, they're giving you ownership of the object. The object will only be destroyed when your std::unique_ptr is destroyed (which will be when your Dependent is destroyed, since it is a member).
Alternatively, if you take a std::shared_ptr then the object will be destroyed once both the client's and your std::shared_ptrs are destroyed.
sftrabbit has some good advice, to which I'd add:
you could create a virtual clone() method in the abstract base class (it's not a virtual base class - that's something else entirely); that method would be implemented in the derived interest rate classes, returning a pointer to a new independent interest rate object that can be owned by the Option; this is particularly useful if the objects contain data that changes as you use it (e.g. from calculations or caching)
you probably don't want this, but with std/boost shared pointers it's also possible to ask for a weak pointer to the shared object... that way you can test whether the "owners" of the object (which won't include you) have already finished with it and triggered its destruction
Separately, to use runtime polymorphism your ExogenousVariationA and ~B classes must actually derive from Exogenous, and the method you want to be polymorphically dispatched must be virtual. That looks like this:
class Exogenous
{
public:
virtual double interfaceMethod() const=0;
}
class ExogenousVariationA : public Exogenous
{
public:
double interfaceMethod() const { return resultA; }
}

What exactly does getinstance() do in a singleton?

I have come across the singleton pattern.
I was unable to understand the difference between
singletonobj.getinstance().dosomething() //1st one
and
singletonobj.dosomething() //2nd one
What does getinstance() do, that isn’t being done in the second case?
Well, technically, singletonobj.getinstance() is redundant, because that means you already got a hold of the object.
The call would usually look something like:
SingletonClass::getinstance().dosomething();
or
singletonobj.dosomething()
in case you pre-fetched the object - i.e. previously did
SingletonClass& singletonobj = SingletonClass::getinstance();
First, singletonobj is a wrong/confusing name. Singletons are called on a class basis, like:
Log::getInstance().doSomething();
and not
Log log = new Log;
log.getInstance().doSomething();
So this should answer the question, but I'll detail anyway :)
Log::doSomething();
would force doSomething() to be a static method, while
Log::getInstance().doSomething();
has doSomething() as an instance method.
Why use getInstance()? Because a singleton, by its very definition, should only have zero or one instances. By making the constructor for a singleton private and publishing the getInstance() method, it allows you to control how many instances of this class there are. The private constructor is simply to avoid other classes to instance this class, which would defeat the purpose of this class being a singleton, as you wouldn't be able to control how many instances of this class there are.
class SingletonExample {
private:
static SingletonExample* instance = NULL;
SingletonExample() { }
public:
static SingletonExample getInstance() {
if (instance == NULL) {
instance = new SingletonExample;
}
return *instance;
}
void doSomething() {
// Do something :)
}
}
It would appear that that the first example is calling a regular method, whereas the second example is calling a static method.
The Singleton design pattern ensures that only a single instance of a given object is instantiated at any given time. The first example returns said instance, and then calls a method using an instance of an object.
The second example appears to be using a static method that does not require an instance of an object and actually invalidates the singleton design pattern...

shared_ptr and the this-pointer

OK, I started using shared-pointers and pass shared-pointers as much as possible. No conversion to raw pointers anymore. This works good, except in this specific case:
Suppose we have a class that also is an observer on another class, like this:
class MyClass : public IObserver
{
public:
MyClass (std::shared_ptr<SomeOtherClass> otherClass);
void DoSomethingImportant();
private:
std::shared_ptr<SomeOtherClass> m_otherClass;
};
This class is used like this in my application:
std::shared_ptr<MyClass> myInstance(new MyClass(otherInstance));
...
myInstance->DoSomethingImportant();
MyClass gets a shared-pointer to another class and stores this in its m_otherClass data member.
In the DoSomethingImportant method, the MyClass instance does lots of important things, including registering itself as an observer on m_otherClass, like this:
m_otherClass->registerObserver(this);
The problem is that the registerObserver method is defined like this:
void registerObserver (std::shared_ptr observer);
It expects a shared pointer, but 'this' is a raw pointer, not a shared one.
I see three ways of solving this:
Find a trick to convert a normal pointer to a shared pointer (see question convert pointer to shared_ptr), but the answers to that question only suggest to copy the shared-pointers, not on how to actually convert the pointer to a shared pointer.
Pass the shared-pointer to ourself to the method, like this: "myInstance->DoSomethingImportant(myInstance);" which seems a bit stupid.
Put the observer part into a separate class. This looks like some overkill, and might make the class harder to understand.
This problem makes it obvious that shared-pointers are just an add-on to C++ (I don't think you have the same problem in other languages/environments like C# (or .Net in general) and Java).
Any other suggestions or tricks on how to handle this situation?
What you need is probably the enable_shared_from_this and shared_from_this facilities. The docs are here
Note that you cannot use shared_from_this until the constructor has fully completed and the object is already owned by another shared_ptr.
struct test : boost::enabled_shared_from_this<test>
{
test() {
// shared_from_this(this); // error, still not owned by another shared_ptr
}
boost::shared_ptr<test> shared() {
return shared_from_this(this);
}
};
int main() {
test * t = new test;
// boost::shared_ptr<test> p = t->shared(); // error, not yet owned by other shared_ptr
boost::shared_ptr<test> owner( t );
boost::shared_ptr<test> p = t->shared(); // [*] ok, "owner" owns the object
}
[*] This part of the example is silly, you could just copy owner into p, instead of calling the method. It is just presented to note when it is ok or not to called shared_from_this inside the test methods.
For observer pattern, the observed object doesn't take the ownership of the observer, why not just using a raw pointer? The life cycle of the observer should be controlled by observer itself.
By using enable_shared_from_this, you introduce cycle dependency for the observer and its observed object. That means if not delete explicitly, the resource will never be released.
How about making the constructor private and having a static construction method like this:
class MyClass : public IObserver
{
public:
static std::shared_ptr<MyClass> createObserver(std::shared_ptr<SomeOtherClass> otherClass);
void DoSomethingImportant();
private:
MyClass (std::shared_ptr<SomeOtherClass> otherClass);
std::shared_ptr<SomeOtherClass> m_otherClass;
};
Then you could instantiate the observer cleanly in the static method and not have to worry about the this pointer at all.
Can you move the registration step into a seperate method? :
shared_ptr<SomeOtherClass> other(new SomeOtherClass());
shared_ptr<MyClass> my(new MyClass());
// register myself to the observer
other->registerObserver(my);
my->DoSomethingImportant();
A good design of observer pattern can be implemented with boost::signal and boost::bind
libraries. I encourage you to have a look.
Best Regards,
Marcin