我有一個容器類(即容器)持有shared_ptr初始化不同的 類的基類。我已經實現了這個想法,如下面的代碼。將shared_ptr參數添加到容器的有效方法?
問題1>總體而言,你可以找到下面的代碼的任何潛在的問題? 我對最佳做法感興趣,並且當前通過vs2010和 的代碼已輸出預期結果。
問題2>難道我設計集裝箱::添加簽名,以便 客戶需要在一個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;
}
可能更好地放在CodeReview上? –
那是哪裏?你能告訴我這個位置嗎? – q0987
你可以在這裏找到它:http://codereview.stackexchange.com/questions :) –