D
Dave Rahardja
Sorry, I was thinking about auto variables, however as a practical
matter not being able to destroy what you create can be a big problem.
As a general rule, yes. However, there are times where the Abstract Factory
pattern makes this pattern desirable:
class Widget
{
public:
/* ... */
virtual void fn() = 0;
private:
virtual ~Widget();
friend class AbstractFactory;
};
class WidgetA: public Widget
{
public:
/* ... */
virtual void fn();
};
class WidgetB: public Widget
{
public:
/* ... */
virtual void fn();
};
class AbstractFactory
{
public:
/* ... */
AbstractFactory& createFactory();
// Create either WidgetA or WidgetB
Widget& createWidget();
void destroyWidget(Widget&);
};
int main()
{
AbstractFactory& factory = AbstractFactory::createFactory();
Widget& widget = factory.create();
factory.destroy(widget);
/* ... */
}
Why not just overload the delete operator in Widget? Because then Widget needs
to know about AbstractFactory, and Widget potentially needs to carry a
reference to the Abstractfactory instance.
-dr