different ways of creating smart pointers to array

  c++

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.

  1. std::unique_ptr<int[]> p1 = std::make_unique<int[]>(new int[5]); // most common pattern I saw, valid since C++11 
    
  2. std::unique_ptr<int[]> p2 = std::make_unique<int[]>(5); // does this create an array of 5 elements? How can I check that?
    
  3. 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. 
    
  4. std::shared_ptr<int[]> p4 = std::make_shared<int[]>(5); // This seems to be valid after C++17? 
    
  5. std::shared_ptr<int[]> p5 = std::make_shared<int[]>(new int[5]); 
    
  6. std::shared_ptr<int[]> p6(new int[5], std::default_delete<int[]>());
    
  7. 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++

LEAVE A COMMENT