Is there any way to provide a custom destructor/destroy function with

M

Mears

I'm pretty sure the answer is no, but thought I'd check. I'm trying
to protect a pointer to a C-based struct that needs to be deallocated
through an API call.

I was thinking of simply creating a wrapper class for the struct that
calls the API function in its destructor, but I'm hoping there is a
cleaner way of doing this.
 
K

Kira Yamato

I'm pretty sure the answer is no, but thought I'd check. I'm trying
to protect a pointer to a C-based struct that needs to be deallocated
through an API call.

I was thinking of simply creating a wrapper class for the struct that
calls the API function in its destructor, but I'm hoping there is a
cleaner way of doing this.

Can you declare the new and delete operators for the struct?
 
S

Stuart Redmann

Mears said:
I'm pretty sure the answer is no, but thought I'd check. I'm trying
to protect a pointer to a C-based struct that needs to be deallocated
through an API call.

I was thinking of simply creating a wrapper class for the struct that
calls the API function in its destructor, but I'm hoping there is a
cleaner way of doing this.

Creating the wrapper class would be my first choice. If you need the auto_ptr
behaviour (the concept of ownership of the underlying plain pointer), you had
better derive your wrapper class from auto_ptr, and provide your own version of
the destructor (and possibly your own version of a constructor, so that you get
rid of any plain API calls).

Regards,
Stuart
 
M

Mears

Creating the wrapper class would be my first choice. If you need the auto_ptr
behaviour (the concept of ownership of the underlying plain pointer), you had
better derive your wrapper class from auto_ptr, and provide your own version of
the destructor (and possibly your own version of a constructor, so that you get
rid of any plain API calls).

Regards,
Stuart

I don't think I can safely override auto_ptr. The problem is that the
auto_ptr's destructor would be called after my derived class's
destructor and proceed to free (with delete) memory I had previously
deleted with an API call in my derived class's destructor.

What I meant by wrapper was something similar to:

class SemWrapper{
public:
SemWrapper(<options>){
mSem = semCreate(<options>);
}

~SemWrapper(){
semDelete(mSem);
}

sem_id getSem(){return mSem);
private:
sem_id mSem;
};


Then to use it, I would simply:
auto_ptr<SemWrapper> sem(new SemWrapper);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,186
Messages
2,570,998
Members
47,587
Latest member
JohnetteTa

Latest Threads

Top