According to this paper, one of the common mistakes developers make ( #3 ) is using a smart pointer with array types; Mainly because the operator delete
will be called instead of delete[]
, leaving the program with a memory leak.
Depite that; looking up default deleter in the C reference, the following code is there:
#include <memory>
#include <vector>
#include <algorithm>
int main()
{
// {
// std::shared_ptr<int> shared_bad(new int[10]);
// } // the destructor calls delete, undefined behavior
{
std::shared_ptr<int> shared_good(new int[10], std::default_delete<int[]>());
} // the destructor calls delete[], ok
{
std::unique_ptr<int> ptr(new int(5));
} // unique_ptr<int> uses default_delete<int>
{
std::unique_ptr<int[]> ptr(new int[10]);
} // unique_ptr<int[]> uses default_delete<int[]>
// default_delete can be used anywhere a delete functor is needed
std::vector<int*> v;
for(int n = 0; n < 100; n)
v.push_back(new int(n));
std::for_each(v.begin(), v.end(), std::default_delete<int>());
}
Which directly contradicts that; But this might be because of different C standards; Is this the case, or is #3 in the paper simply untrue?
Does a deleter needs to be provided explicitly when using arrays with smart pointers, or does it depend on the c standard ( e.g. different behaviour in C 11 or c 17; c 20 ); or the platform (e.g. gcc, MSVC etc.. )?
CodePudding user response:
If I understand correctly, you seem to think that the example 4 contradicts the paper, and the paper recommends using example 2. This is not what the paper is saying.
Example 1 is undefined behavior, as described in the paper: "Using smart pointers, such as auto_ptr, unique_ptr, shared_ptr, with arrays is also incorrect."
Example 2 works correctly, however using a custom deleter is not mentioned in the paper at all.
Example 3 creates pointer to single int
. This is not related to the paper.
Example 4 creates pointer to int[]
, which is mentioned in the paper as a valid usage: "If using of a smart pointer is required for an array, it is possible to use -- a unique_ptr<T[]> specialization."