- 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.11 Smart Pointers to const and const Smart Pointers
Raw pointers allow two kinds of constness: the constness of the pointed-to object and that of the pointer itself. The following is an illustration of these two attributes4:
const Something* pc = new Something; // points to const object pc->ConstMemberFunction(); // ok pc->NonConstMemberFunction(); // error delete pc; // ok (surprisingly) Something* const cp = new Something; // const pointer cp->NonConstMemberFunction(); // ok cp = new Something; // error, can't assign to const pointer const Something* const cpc = new Something; // const, points to const cpc->ConstMemberFunction(); // ok cpc->NonConstMemberFunction(); // error cpc = new Something; // error, can't assign to const pointer
The corresponding uses of SmartPtr look like this:
// Smart pointer to const object SmartPtr<const Something> spc(new Something); // const smart pointer const SmartPtr<Something> scp(new Something); // const smart pointer to const object const SmartPtr<const Something> scpc(new Something);
The SmartPtr class template can detect the constness of the pointed-to object either through partial specialization or by using the TypeTraits template defined in Chapter 2. The latter method is preferable because it does not incur source-code duplication as partial specialization does.
SmartPtr imitates the semantics of pointers to const objects, const pointers, and the combinations thereof.