Re: Can auto_ptr<> be used with void and malloc()/free()
On May 3, 1:02 pm, "bob" <rob...@robert.org> wrote:
Hi,
I need to allocate a variable size struct using malloc() and then free it
using free(). Is there a way I could wrap a pointer returned from mall=
oc()
in auto_ptr<>? I've used auto_ptr<> with objects of struct/class but o=
nly
when they were allocated using new() operator. AFAIK, it is generally =
not
safe to allocate with malloc() and then free with delete().
Example:
struct {
int x;
int y;
unsigned char data[1];
} structA;
structA* pa = (structA*) malloc(100);
I'd like to wrap pa pointer in auto_ptr<> so I do not have to worry about
freeing it when I leave a given block.
I think I could do the following:
unsigned char* p = new unsigned char[100];
structA* pa = (structA*) p;
_auto_ptr<unsigned char> ptrA(p);
[...]
Any thoughts?
Sorry to drop in late, but here's something no one suggested: use
shared_ptr, which supports custom deallocation. (auto_ptr implements
single-owner ownership, whereas shared_ptr implements shared
ownership, so I think shared_ptr can be used as a replacement for
auto_ptr if you want.)
#include <stdlib.h>
#include <memory>
using namespace std::tr1;
// Your C-compatible struct
struct PacketData
{
int x;
int y;
unsigned char data[1];
};
struct PacketDataDeleter
{
void operator()(PacketData* pd)
{
free(pd);
}
};
// Suppose this is the function that reads from the
// network and assembles a PacketData
PacketData* ReadPacketData();
// Example usage
void DoSomething()
{
shared_ptr<PacketData> pd(ReadPacketData(), PacketDataDeleter());
// use pd
}