Efficient way to add shared_ptr parameter to a container?
I have a container class(i.e. Container) that holds shared_ptr initialized by different subclass of class Base. I have implemented the idea as the following code.
Question 1> Overall, can you find any potential problems in the following code? I am interested in the best practice and also the currently code passed vs2010 and output the expected results already.
Question 2> Is it the right way that I design the Container::Add signature so that the client needs to pass in a shared_ptr?
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Base
{
public:
virtual void PrintMe(void) = 0;
virtual ~Base() = 0 {} // **Updated based on comments from [bdonlan]**
};
class SubClassA : public Base
{
public:
virtual void PrintMe(void)
{ cout << "This is SubClassA" << endl; }
};
class SubClassB : public Base
{
public:
virtual void PrintMe(void)
{ cout << "This is SubClassB" << endl; }
};
typedef std::shared_ptr<Base> BasePtr;
typedef std::vector<BasePtr>::iterator VecIter;
class Container
{
public:
void Add(BasePtr ptr)
{ vec.push_back(ptr); }
void PrintAll()
{
for ( VecIter iter = vec.begin() ; iter < vec.end(); ++iter )
{ (*iter)->PrintMe(); }
}
private:
vector<BasePtr> vec;
};
int _tmain(int argc, _TCHAR* argv[])
{
Container con;
BasePtr ptrA(new SubClassA);
BasePtr ptrB(new SubClassB开发者_开发知识库);
con.Add(ptrA);
con.Add(ptrB);
con.PrintAll();
return 0;
}
You need to add a virtual destructor to Base
; the BasePtr
shared pointer will try to delete the subclasses as a Base *
, but this is only legal if Base
has a virtual ~Base
. It should be enough just to add a public virtual ~Base() { }
to the Base
class body.
Apart from that I don't really see any major problems.
精彩评论