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.. )?