I am learning how to use a smart pointer for an array and there seem to be many ways to do that with shared_ptr and unique_ptr. I want to make sure my following examples are all valid.
-
std::unique_ptr<int[]> p1 = std::make_unique<int[]>(new int[5]); // most common pattern I saw, valid since C++11
-
std::unique_ptr<int[]> p2 = std::make_unique<int[]>(5); // does this create an array of 5 elements? How can I check that?
-
struct Deleter { void operator()(int* p) { delete[] p; } }; std::shared_ptr<int[], Deleter> p3 {new int[5], Deleter()}; // before C++17? Without Deleter, delete[] won't be called.
-
std::shared_ptr<int[]> p4 = std::make_shared<int[]>(5); // This seems to be valid after C++17?
-
std::shared_ptr<int[]> p5 = std::make_shared<int[]>(new int[5]);
-
std::shared_ptr<int[]> p6(new int[5], std::default_delete<int[]>());
-
std::shared_ptr<int[], std::default_delete<int[]>> p7(new int[5], std::default_delete<int[]>()); // why this has compilation error whereas option 3 could compile?
Edit:
For option 2, I replaced int
with a class and I put print in the class constructor. After running it, the output shows that the constructor is called 5 times. So it seems to be a valid option.
Source: Windows Questions C++