Consider following code:
#include
// =============================
class Shape{
public:
virtual ~Shape(){};
virtual void process
Your factories are passing around ownership. There's another alternative to that aspect; instead of passing around ownership, you can make the factory own the objects:
class Factory {
public:
~Factory() { for(int i=0;i<vec.size();i++) delete vec[i]; }
Shape &build_obj() {
Shape *sh = new Triangle;
vec.push_back(sh);
return *sh;
}
private:
void operator=(const Factory &);
std::vector<Shape*> vec;
};
I think the most idiomatic modern C++ method is the one you mention in passing but ignore. Return a std::unique_ptr<Shape>
.
It is safe, clearly expresses ownership, supports polymorphism and doesn't need much code.
class ShapeFactory {
public:
std::unique_ptr<Shape> create(){
return std::make_unique<Triangle>();
}
};
But I wouldn't want to claim it was the "best" method.
Your PimplShape
in option 3 is actually very similar to a unique_ptr
just less generic or tested.