1
我想知道是否会出现任何问题,如果我使用vector.Im矢量的智能指针,将容纳派生对象(包括其他容器)的容器对象,我想用智能指针用于自我删除,并希望将unique_ptr用于单一所有权,但在这种情况下不能使用它。智能指针或矢量矢量的常规指针
每个容器都有一个大小,所以最后一个容器不能包含第一个容器,这将防止读取shared_pt的问题之一。
class Base{...}
class Item:public Base{...}
class Container : public Base{
//int size;
vector<shared_ptr<Base>>vec;
public:
template <typename D>
void AddItem(const D& thing) {
vec.push_back(make_shared<D>(thing));
}
};
Container bag;
Item thing;
Container bag2;
bag2.AddItem<Item>(thing);
bag.AddItem<Container>(bag2);
// _________________________
相关,为什么不这项工作
class Container :public Base{
vector<Base*>slot;
public:
~Container(){}
void Add(Base* thing){ slot.push_back(thing); }
void Delte_All()
{
for(int i=0;i<slot.size();++i)
{
delete slot[i];
cout << "Object " << i << " deleted" <<endl;
}
slot.clear();
}
};
int main()
{
Container bag;
Container bag2;
Base* thing=&bag2;
bag.Add(thing);
bag.Delte_All();
return 0;
}
你的第一个案例
你可以使用'std :: vector >>' –