Re: Can auto_ptr<> be used with void and malloc()/free()
Ulrich Eckhardt wrote:
bob wrote:
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
malloc() in auto_ptr<>?
No, auto_ptr uses delete, which you must not use with a pointer returned
from malloc. What I'm not sure about is whether you could override
operators new/delete for your struct and redirect these accordingly to do
The Right Thing(tm). I'd try asking this in comp.lang.c++.moderated.
Without claiming that this is portable, it seems to do the right thing under
GCC 4:
struct var
{
size_t len;
unsigned char content[0];
#ifdef __cplusplus
static auto_ptr<var> create(size_t len)
{
void* ptr = malloc(sizeof (var) + len);
printf("create() = %p\n", ptr);
if(!ptr)
throw std::bad_alloc();
auto_ptr<var> res(static_cast<var*>(ptr));
res->len = len;
return res;
}
auto_ptr<var> clone() const
{
auto_ptr<var> res = create(len);
memcpy(res.get(), this, sizeof (var) + len);
return res;
}
void operator delete(void* ptr)
{
printf("delete(%p)\n", ptr);
free(ptr);
}
private:
// private constructor, use create()
var(){}
// not copyable, use clone()
var(var const&);
// not assignable
var& operator=(var const&);
#endif
};
Cheers!
Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932