Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RAII with a character pointer

I see a lot of RAII example classes wrapping around file handles.

I have tried to adapt these examples without luck to a character pointer.

A library that I am using has functions that take the address of a character pointer (declared like get_me_a_string(char **x)). These functions allocate memory for that character pointer and leave it up to the end user of the library to clean it up in their own code.

So, I have code that looks like this...

char* a = NULL;
char* b = NULL;
char* c = NULL;

get_me_a_string(&a);
if(a == NULL){
    return;
}


get_me_a_beer(&b);
if(b == NULL){
    if(a != NULL){
        free(a);
    }
    return;
}


get_me_something(&c);
if(c == NULL){
    if(a != NULL){
        free(a);
    }
    if(b != NULL){
        free(b);
    }
    return;
}

if(a != NULL){
    free(a);
}
if(b != NULL){
    free(b);
}
if(a != NULL){
    free(b);
}

It sounds like RAII is the answer for this mess that I have above. Could someone provide a simple C++ class that wraps a char* rather than a FILE*?

Thanks

like image 314
eric.frederich Avatar asked Feb 27 '23 16:02

eric.frederich


1 Answers

There's something available already in the standard library: it's called std::string.

Edit: In light of new information:

It will allocate memory and fill it up. I could copy the contents into a new std::string object but I'd still have to free the memory that was allocated by the function.

This is poor design on the implementor's part -- the module that allocates should be responsible for deallocation.

Okay, now that I've got that out of my system: you could use a boost::shared_ptr for freeing.

template<typename T>
struct free_functor
{
    void operator() (T* ptr)
    {
        free(ptr);
        ptr=NULL;            
    }
};
shared_ptr<X> px(&x, free_functor());
like image 160
dirkgently Avatar answered Mar 11 '23 08:03

dirkgently