首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用shared_ptr的例子?

使用shared_ptr的例子?
EN

Stack Overflow用户
提问于 2010-08-13 20:48:25
回答 5查看 170.8K关注 0票数 82

嗨,今天我问了一个关于How to insert different types of objects in the same vector array 的问题,我在这个问题中的代码是

代码语言:javascript
复制
 gate* G[1000];
G[0] = new ANDgate() ;
G[1] = new ORgate;
//gate is a class inherited by ANDgate and ORgate classes
class gate
{
 .....
 ......
 virtual void Run()
   {   //A virtual function
   }
};
class ANDgate :public gate 
  {.....
   .......
   void Run()
   {
    //AND version of Run
   }  

};
 class ORgate :public gate 
  {.....
   .......
   void Run()
   {
    //OR version of Run
   }  

};      
//Running the simulator using overloading concept
 for(...;...;..)
 {
  G[i]->Run() ;  //will run perfectly the right Run for the right Gate type
 } 

我想使用向量,所以有人写道我应该这样做:

代码语言:javascript
复制
std::vector<gate*> G;
G.push_back(new ANDgate); 
G.push_back(new ORgate);
for(unsigned i=0;i<G.size();++i)
{
  G[i]->Run();
}

但是后来他和其他许多人建议我最好使用Boost pointer containers

shared_ptr。在过去的3个小时里,我一直在阅读这个主题,但文档对我来说似乎相当高级。*谁能给我一个shared_ptr用法的小代码示例,以及为什么他们建议使用shared_ptr。还有其他类型,如ptr_vectorptr_listptr_deque*

Edit1:我也读过一个代码示例,其中包括:

代码语言:javascript
复制
typedef boost::shared_ptr<Foo> FooPtr;
.......
int main()
{
  std::vector<FooPtr>         foo_vector;
........
FooPtr foo_ptr( new Foo( 2 ) );
  foo_vector.push_back( foo_ptr );
...........
}

而且我不懂语法!

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3476938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档