- 1 Smart Pointers 101
- 2 The Deal
- 3 Storage of Smart Pointers
- 4 Smart Pointer Member Functions
- 5 Ownership Handling Strategies
- 6 The Address-of Operator
- 7 Implicit Conversion to Raw Pointer Types
- 8 Equality and Inequality
- 9 Ordering Comparisons
- 10 Checking and Error Reporting
- 11 Smart Pointers to const and const Smart Pointers
- 12 Arrays
- 13 Smart Pointers and Multithreading
- 14 Putting It All Together
- 15 Summary
- 16 SmartPtr Quick Facts
7.12 Arrays
In most cases, instead of dealing with heap-allocated arrays and using new[] and delete[], you're better off with std::vector. The standard-provided std::vector class template provides everything that dynamically allocated arrays provide, plus much more. The extra overhead incurred is negligible in most cases.
However, "most cases" is not "always." There are many situations in which you don't need and don't want a full-fledged vector; a dynamically allocated array is exactly what you need. It is awkward in these cases to be unable to exploit smart pointer capabilities. There is a certain gap between the sophisticated std::vector and dynamically allocated arrays. Smart pointers could close that gap by providing array semantics if the user needs them.
From the viewpoint of a smart pointer to an array, the only important issue is to call delete[] pointee_ in its destructor instead of delete pointee_. This issue is already tackled by the Ownership policy.
A secondary issue is providing indexed access, by overloading operator[] for smart pointers. This is technically feasible; in fact, a preliminary version of SmartPtr did provide a separate policy for optional array semantics. However, only in very rare cases do smart pointers point to arrays. In those cases, there already is a way of providing indexed accessing if you use GetImpl:
SmartPtr<Widget> sp = ...; // Access the sixth element pointed to by sp Widget& obj = GetImpl(sp)[5];
It seems like a bad decision to strive to provide extra syntactic convenience at the expense of introducing a new policy.
SmartPtr supports customized destruction via the Ownership policy. You can therefore arrange array-specific destruction via delete[]. However, SmartPtr does not provide pointer arithmetic.