I have read several answers about similar issues, but I am still confused as to when it is a good time to use smart pointers. I have a class Foo
which looks like this:
class Bar;
class Baz;
class Foo
{
public:
Foo(Bar* param1, std::vector<Baz*>& param2);
virtual ~Foo();
// Method using myBar and myBaz polymorphically...
private:
Bar* myBar;
std::vector<Baz*> myBaz;
};
I need the two data members to be pointer for polymorphism. It is part of an API and what I fear is that someone writes:
int main()
{
//...
std::vector<Baz*> allOnHeap {new Baz(), new Baz()};
Foo(new Bar(), allOnHeap);
// ...
}
which would be legal but would result in memory leaks. I could add delete
s in
the destructor, but then what if no dynamic allocation has been
made? In your opinion, would it be a good idea to use smart
pointers in this case? Please explain your opinion. If you have better ideas on how to do this, please feel free to share it.