I have the following piece of code:
// Read the file into this char array.
std::unique_ptr<char> chars(new char[size + 1]); // Not using unique_ptr<int[]> ??
chars.get()[size] = '\0';
for (size_t i = 0; i < size;) {
i += fread(&chars.get()[i], 1, size - i, file);
if (ferror(file)) {
fclose(file);
return MaybeLocal<String>();
}
}
fclose(file);
As you can see it, it is using std::unique_ptr<char>
to hold the result of new[]
, but not using std::unique_ptr<char[]>
. If I recall it correctly, the default deleter of a std::unique_ptr
just calls delete
or delete[]
, depending on the template parameter is an array or not. It means I can simplified the above code to
char *chars = new char[size + 1];
delete chars;
The code above seems to violate the principle that in general you should use delete[]
to dispose what you new[]
out.
- It is legal to manage a dynamic array via non-array
std::unique_ptr
? - It is legal not to pair the
new
anddelete
w.r.t to array-ness? Or does it matter in practice?
Edit: I have learnt that mispairing new
, delete
and new[]
, delete[]
is undefined behaviour. Before being tagged as a possible duplicate, I update my post to ask whether this unique_ptr
is also an UB?