boost::智能指针奇怪的析构顺序。

来源:互联网 发布:全球手机电视直播软件 编辑:程序博客网 时间:2024/06/05 05:11
// MyServer.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <conio.h>#include <boost/function.hpp>#include <vector>#include <boost/bind.hpp>#include <boost/asio.hpp>#include <boost/thread.hpp>#include <conio.h>#include <boost/shared_ptr.hpp>#include <boost/make_shared.hpp>#include "cell.h"using namespace std;using namespace boost;class ICommand{public:virtual void Execute() = 0;virtual ~ICommand() { }};class DoCommand : public ICommand{private:int n_;public:DoCommand(int n) : n_(n) {//cout << "DoCommand()" << endl;}void Execute(){cout << "DoCommand::Execute() n = " << n_ << endl;}~DoCommand(){cout << "~DoCommand " << n_ << endl;}};class AllocCommand : public ICommand{private:intm_MemorySize;int*m_pMemory;public:AllocCommand(int memorySize) : m_MemorySize(memorySize), m_pMemory(new int[m_MemorySize]){//cout << "AllocCommand " << m_MemorySize << "bytes, address = " << m_pMemory << endl;}~AllocCommand(){cout << "~AllocCommand " << m_MemorySize << endl;delete[] m_pMemory;m_pMemory = NULL;m_MemorySize = 0;}void Execute(){cout << "AllocMemory::Execute() n = " << m_MemorySize << endl;}};void RunIoService(boost::asio::io_service& ios){while(1){try{ios.run();break;}catch(...){}}}typedef function<void ()> FCommand;typedef boost::shared_ptr<FCommand> CommandPtr;void HandleEvent(CommandPtr pCommand){(*pCommand)();}void StopService(boost::asio::io_service& ios){while(1){if(_kbhit()){ios.stop();break;}}}int _tmain(int argc, _TCHAR* argv[]){boost::shared_ptr<AllocCommand> pAlloc;boost::shared_ptr<DoCommand> pDo;std::vector<CommandPtr> cmdArray;std::vector<boost::weak_ptr<FCommand> > weakArray;cmdArray.reserve(100);for (int i = 1; i <= 10; ++i){CommandPtr pCmd;boost::weak_ptr<FCommand> weak;if (i % 2){pAlloc = boost::make_shared<AllocCommand>(i);//pCmd.reset(new FCommand(bind(&ICommand::Execute, pAlloc)));pCmd = boost::make_shared<FCommand>(bind(&ICommand::Execute, pAlloc));}else{pDo = boost::make_shared<DoCommand>(i);//pCmd.reset(new FCommand(bind(&ICommand::Execute, pDo)));pCmd = boost::make_shared<FCommand>(bind(&ICommand::Execute, pDo));}weak = pCmd;weakArray.push_back(weak);cmdArray.push_back(pCmd);}//TcpServer tcpServer;Cell c;c.StartCell();boost::thread s(&StopService, boost::ref(c.GetIoService()));boost::shared_ptr<boost::asio::io_service::strand> strand1 = c.GetStrand();boost::shared_ptr<boost::asio::io_service::strand> strand2 = c.GetStrand();for (int i = 0; i < cmdArray.size(); ++i){if(i%2)strand1->post(boost::bind(&HandleEvent, cmdArray[i]));elsestrand2->post(boost::bind(&HandleEvent, cmdArray[i]));}s.join();//c.StopCell();return 0;}为什么析构时1,2,3,4,5,6,7,8,10,9.最后两位数据顺序不对?

多次测试都是10先析构,然后是9.这样虽然没什么大问题(主要是任务串行化了),但是如果和pool结合时,感觉会给pool带来效率的影响。
原创粉丝点击