【发布时间】:2011-06-01 04:21:48
【问题描述】:
class ByteBuffer
{
public:
ByteBuffer(std::shared_ptr<uint8_t> buf, int len);
explicit ByteBuffer(int len);
virtual ~ByteBuffer(void);
std::shared_ptr<uint8_t> getBuffer() const {return this->buffer;}
uint16_t getLength() const {return this->length;}
private:
std::shared_ptr<uint8_t> buffer;
uint16_t length;
};
//-----------------------------------------------------------------------------
ByteBuffer::ByteBuffer(std::shared_ptr<uint8_t> buf, int len)
: buffer(buf),length(len)
{ }
ByteBuffer::ByteBuffer(int len)
: buffer(new uint8_t[len]),length(len)
{ }
ByteBuffer::~ByteBuffer(void)
{ }
//-----------------------------------------------------------------------------
class Packet
{
public:
explicit Packet(ByteBuffer& ref);
virtual ~Packet(void);
};
Packet::Packet(ByteBuffer& ref)
{
// how do i intinlize it here so i can use it?
}
// i have onther method for the handling
void HandlePacket(Packet & pack);
Handel(ByteBuffer & ref)
{
Packet p(ref);
HandlePacket(p); // the error happens here
}
编辑:对不起,我忘了添加发生错误的方法我很抱歉
你可以看到 2calsss,但是每次我试图在数据包中传递字节缓冲区然后使用其他方法中的数据包它给我这个错误:
AccountServer.exe 中 0x00051526 处的未处理异常:0xC0000005:访问冲突读取位置 0x00000004。
所以我的问题是我该如何解决这个问题!?
【问题讨论】:
-
是什么让你认为
shared_ptr<>甚至可以在没有自定义删除器的情况下使用new[]分配的指针? -
@ildjarn shared_ptr 在它讨厌零时处理它,它会自动删除它,这就是我使用智能指针的原因
-
@Mixed
shared_ptr没有自定义删除器不能用于删除分配有new[]的指针,为此使用shared_array。 -
只需将
std::vector<>用作您的缓冲区(而不是ByteBuffer),这正是它的用途。 -
@frag:总是未定义的行为,类型无关紧要。
new匹配delete,new[]匹配delete[]。