很长一段时间后,我相信我的代码的问题是我有多个智能指针引用同一个对象,这导致该对象被多个智能指针删除。我在不偏离程序概念的情况下尽可能地压缩了代码。
目前,我得到的错误是一个段。过错。我相信我的双重引用是在这一行创建的。
newProtocol->SetCPU(CPUPtr(this));
我的问题是对同一个对象的双重引用吗?如果是,我该如何解决?
#include <iostream>
#include <map>
using namespace std;
#include "boost/weak_ptr.hpp"
#include <boost/shared_ptr.hpp>
class TCPProtocol;
class CPU;
class TCPConnection;
typedef boost::shared_ptr<TCPProtocol> TCPProtocolPtr;
typedef boost::shared_ptr<CPU> CPUPtr;
typedef boost::shared_ptr<TCPConnection> TCPConnectionPtr;
class Protocol
{
public:
string GetName() const;
string _name;
};
class TCPProtocol : public Protocol
{
public:
static TCPProtocolPtr Create(){return(TCPProtocolPtr(new TCPProtocol()));}
static TCPProtocolPtr Create(const TCPProtocol &Protocol
{
return(TCPProtocolPtr(new TCPProtocol(Protocol)));
}
void SetCPU(boost::shared_ptr<CPU> CPU){ _CPU = CPU; }
protected:
boost::weak_ptr<CPU> _CPU;
};
class CPU
{
public:
typedef std::map<std::string, TCPProtocolPtr> ProtocolMap;
public:
CPU(const CPU& obj);
CPU(TCPConnectionPtr connection){}
static CPUPtr Create(const TCPConnectionPtr connection)
{
return(CPUPtr(new CPU(connection)));
}
void AddProtocol(const TCPProtocolPtr ProtocolPtr);
void SetCPU(boost::shared_ptr<CPU> CPU);
ProtocolMap Protocols();
const ProtocolMap Protocols() const;
ProtocolMap _Protocols;
};
class TCPConnection
{
public:
static TCPConnectionPtr Create()
{
return(TCPConnectionPtr(new TCPConnection()));
}
void SetVersion(int version){ _version = version; }
private:
int _version;
};
int main()
{
//Create a connection to an CPU
TCPConnectionPtr CPUConnection = TCPConnection::Create();
//Define needed connection parameters
CPUConnection->SetVersion(123);
//Create an CPU
CPUPtr CPU = CPU::Create(CPUConnection);
//Create an instance of TCPProtocol
TCPProtocolPtr ProtocolPtr = TCPProtocol::Create();
//Add the protocol to the CPU
CPU->AddProtocol(ProtocolPtr);
}
CPU::CPU(const CPU& obj)
{
//Iterate through rhs map and insert its pairs into the lhs map
for(ProtocolMap::const_iterator i = obj._Protocols.begin();
i != obj._Protocols.end(); ++i)
{
TCPProtocolPtr p = TCPProtocol::Create();
*p = *(i->second);
AddProtocol(p);
}
}
void CPU::AddProtocol(const TCPProtocolPtr ProtocolPtr)
{
TCPProtocolPtr newProtocol = TCPProtocol::Create(*ProtocolPtr);
std::string name = newProtocol->_name;
newProtocol->SetCPU(CPUPtr(this));
_Protocols[name] = newProtocol;
}