Re: Can auto_ptr<> be used with void and malloc()/free()
bob wrote:
Thanks to everyone who replied to my post.
It looks like I have to get rid of malloc()/free() or forget about
auto_ptr<> and deal with deallocating memory manually.
For those interested, the reason that I'm using a variable length struct is
that I receive it from a network as a stream of bytes. The first couple of
bytes represent a header and the length of variable size data that follows.
I have a low-level c routine that deals with assembling the packet and then
returns it to clients. Currently the routine allocates ram for the packet
and the client frees it. Quite often logic on the client gets a bit
complicated and ideally I'd like to use auto_ptr<> so I do not need to worry
about freeing the memory allocated in the c routine.
Is it a requirement that the low-level be C? One thing you might try
is redoing your struct like this:
struct structA {
int x;
int y;
std::vector<unsigned char> data;
};
You can then return this structure by value to the client code. When
they are done using it, the memory will clean itself up. If you don't
like to return by value, you could put the structA into an auto_ptr
and return that:
structA read_socket(socket & sock)
{
unsigned char buffer[256] = {0};
buffer << sock;
structA packet;
packet.data.insert(data.begin(), buffer, buffer+255);
return packet;
}
or
std::auto_ptr<structA> read_socket(socket & sock)
{
unsigned char buffer[256] = {0};
buffer << sock;
std::auto_ptr<structA> packet(new structA);
packet->data.insert(data.begin(), buffer, buffer+255);
return packet;
}
Also as Richard said, you could leverage a constructor/destructor into
the structA to simplify the interface even more.