I l@ve RuBoard |
![]() ![]() |
7.11 Smart Pointers to const and const Smart PointersRaw 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 attributes: const Something* pc = new Something; // points to const object pc->ConstMemberFunction(); // ok pc->NonConstMemberFunction(); // error delete pc; // ok (surprisingly)[4] 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. |
I l@ve RuBoard |
![]() ![]() |