Pete Becker
Pete Becker

Reputation: 76245

Why doesn't the obvious use of `std::shared_ptr<T[]>` work?

Seems like the obvious use of std::shared_ptr<T[]> (added with C++ 17) is to hold a pointer to T, and use delete[] when it's time to destroy the managed object. But this code:

#include <memory>

int main() {
    std::shared_ptr<int[]> sp(new int[3]);
    return 0;
}

doesn't compile with any of the online compilers I've tried. In all cases, the error message is a variant of this:

/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/memory:3759:18: note: candidate template ignored: requirement 'is_convertible<int *, int (*)[]>::value' was not satisfied [with _Yp = int] explicit shared_ptr(_Yp* __p,

that is, the constructor that takes a pointer gets SFINAED out because the pointer to the element type isn't convertible to a pointer to array. That seems to be required in the C++ 17 standard and in C++ 20.

Is that really what's intended? How can I use that constructor? Or, alternatively, how do I create a std::shared_ptr object that correctly manages an array without explicitly specifying a deleter?

Upvotes: 6

Views: 309

Answers (1)

Fedor
Fedor

Reputation: 21099

Your program is valid and it should work. The error: no matching constructor for initialization of 'std::shared_ptr<int []>' was only in Clang with its libc++ standard library implementation till the version 10, and it was fixed in version 11. Resolved bug.

Online demo: https://gcc.godbolt.org/z/WdbdTTPPj

Upvotes: 2

Related Questions