扫一扫,访问微社区
只需一步,快速开始
使用道具 举报
#include "boost/shared_ptr.hpp" #include <cassert> #include <queue> #include <iostream> using boost::shared_ptr; class A { public: A(){} virtual void say(){ std::cout<<"A saying.."<<std::endl; } }; class B:public A{ public: B(){} virtual void say(){ std::cout<<"B saying.."<<std::endl; } }; int main() { typedef boost::shared_ptr<A> eT; typedef queue<eT> qT; qT q; q.push(eT(new B)); eT tmp=q.front(); (*tmp).say(); }
#include "boost/shared_ptr.hpp" #include <cassert> #include <queue> #include <iostream> using boost::shared_ptr; class A { public: A(){} virtual void say(){ std::cout<<"A saying.."<<std::endl; } virtual ~A(){ std::cout<<"A destructed.."<<std::endl; } }; class B:public A{ public: B(){} virtual void say(){ std::cout<<"B saying.."<<std::endl; } ~B(){ std::cout<<"B destructed.."<<std::endl; } }; int main() { typedef boost::shared_ptr<A> eT; typedef queue<eT> qT; qT q; q.push(eT(new B)); /* eT tmp=q.front();//如果用tmp指向,pop不会造成释放,因为tmp还指向它 tmp->say(); */ (q.front())->say();//这样用的话,pop后会被释放 std::cout<<"Before pop"<<endl; q.pop(); std::cout<<"After pop"<<endl; }
#include "boost/shared_ptr.hpp" #include <cassert> #include <queue> #include <iostream> using boost::shared_ptr; class A { public: A(){} virtual void say(){ std::cout<<"A saying.."<<std::endl; } virtual ~A(){ std::cout<<"A destructed.."<<std::endl; } }; class B:public A{ public: B(){} virtual void say(){ std::cout<<"B saying.."<<std::endl; } ~B(){ std::cout<<"B destructed.."<<std::endl; } }; typedef boost::shared_ptr<A> eT; typedef queue<eT> qT; void test(qT& q){ eT tmp=q.front(); tmp->say(); std::cout<<"Before pop"<<endl; q.pop(); std::cout<<"After pop"<<endl; } int main() { qT q; q.push(eT(new B)); std::cout<<"Before test.."<<std::endl; test(q); std::cout<<"After test.."<<std::endl; return 0; }
Befor test... B sayiing... Before pop... After pop.. B destructed.. A destructed... After test
本版积分规则 发表回复 回帖并转播 回帖后跳转到最后一页
用微信扫一扫互动赢积分
|Archiver|手机版|小黑屋|广告业务Q|工大后院 ( 粤ICP备10013660号 )
GMT+8, 2025-8-30 07:01
Powered by Discuz! X3.5
Copyright © 2001-2024 Tencent Cloud.