Search code examples
c++smart-pointers

smart pointer array deletor


Up to now I've allocated a buffer for some data processing and deleted it afterwards. Since the code got bigger and caught exceptions at some points can occur, i thought about making it safer with a std::unique_ptr and came up with those solutions:

unique_ptr<char, void (*)(void *)> p1( (char*)operator new(bufSize), operator delete);
unique_ptr<char[], void (*)(void *) > p2( (char*)operator new(bufSize), operator delete);

memcpy(&((p1.get())[0]), "xyz", 3);
memcpy(&(p2[0]), "xyz", 3);

char x1 = p1.get()[0];
char x2 = p2[0];

to me the first solutions (p1) seems to be the correct one, but it's tedious to have to write (p1.get())[...]

the second solution would be the convenient one, but here is my question:

std::unique_ptr<T[]> seems to be templated in a special way supporting operator[], which makes me wonder, if i use std::unique_ptr<T[]> with a custom new and delete operation, is there anything that could go wrong with the ``operator[] or any other functions or is the second solution (p2) fine?


Solution

  • std::unique_ptr is specialised for arrays. You can just write the following:

    std::unique_ptr<char[]> str(new char[4]);
    char foo[] = "str";
    std::copy(foo, foo + sizeof(foo), &str[0]);
    

    If that didn’t exist you could do something similar yourself, or you could write a using alias and a make_array function which does the setting up for you and returns the correct type, then using it would be as simple as

    auto str = make_array<char>(4);
    

    … or something like that.