Ok that was just bad, I've seen it doesn't work at all.
The problem as I said is that the constructor of my object is like the
main of the program, because it's a library which is called by something
like
extern "C" Node* create(ostream&out)
{
return new Node(out);
}
otherwise it would be quite easy to have a factory function with an
auto_ptr, but like this how do I manage it?
as i see you made at least 2 errors:
(i) you are creating LOCAL object e and returning pointer to it by
assigning this (which would be discussed later) is wrong, cause when
control flow leaves the scope (in this case this is if(extended){...} )
local object is destructed and pointer would point to nothing which
means UB. You can solve this error by creating Extended in dynamic
memory with new operator. like
Extended *pe = new Extended( this );
(ii) you are trying to assign to this..... if i'm not mistaken it is
const pointer to 'this' object. you can not make assigning, you'll
immediately get error from compiler.
as for you question i think you make things much more complicated.
Ok that was just bad, I've seen it doesn't work at all.
The problem as I said is that the constructor of my object is like the
main of the program, because it's a library which is called by something
like
extern "C" Node* create(ostream &out)
{
return new Node(out);
}
what prevent you to put factory inside create(), assuming that
implementation of create() in you power.
otherwise if library itself create instance of class with predefined
name you can make it as wrapper, proxy for you real class and put
factory as Gert-Jan de Vos suggested you in constructor.
i see it like this. also i toke into account note of Gert-Jan de Vos
It is indeed usually better to also make the Simple case a separate
derived class from Base. In this case you can later modify/extend the
Simple case without changing the Extended case also.
and splited Base class to ImplBase which is actual base and Simple class
responsible for simple non-extended logic.
class Node {
class ImplBase // may be abstract
{
virtual ~ImplBase(){}
};
class Simple : public ImplBase {...};
class Extended : public ImplBase {...};
std::auto_ptr<ImplBase> _pimpl;
std::auto_ptr<ImplBase> create_impl()
{
if (external_condition)
return std::auto_ptr<ImplBase>(new Extended());
return std::auto_ptr<ImplBase>(new Simple());
}
public:
Node( ostream out ):_pimpl( create_impl() )
{
}
};
hope that helps.
BR, RM