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?
std::unique_ptris specialised for arrays. You can just write the following:If that didn’t exist you could do something similar yourself, or you could write a
usingalias and amake_arrayfunction which does the setting up for you and returns the correct type, then using it would be as simple as… or something like that.