Home > Articles > Programming

This chapter is from the book

6.5 Smart Pointer Pattern

In my experience over the last couple of decades leading and managing development projects implemented in C and C++, pointer problems are by far the most common defects and the hardest to identify.

They are common because the pointer metaphor is very low level and requires precise management, but it is easy to forget about when dealing with all possible execution paths. Inevitably, somewhere a pointer is destroyed (or goes out of scope), but the memory is not properly freed (a memory leak), memory is released but nevertheless accessed (dangling pointer), or memory is accessed but not properly allocated (uninitialized pointer). These problems are notoriously dif-ficult to identify using standard means of testing and peer reviews. Tools such as Purify and LINT can identify "questionable practices," but sometimes they flag so many things it is virtually impossible to use the results. The Smart Pointer Pattern is an approach that is mechanistic (medium scope) rather than architectural (large scope) but has produced excellent results.

6.5.1 Abstract

Pointers are by far the most common way to realize an association between objects. The most common implementation of a navigable association is to use a pointer. This pointer attribute is dereferenced to send messages to the target object. The problem with pointers per se is that they are not objects; they are just data. Because they are not objects, the primitive operations you can perform on them are not checked for validity. Thus, we are free to access a pointer that has never been initialized or after the memory to which it points has been freed. We are also free to destroy the pointer without releasing the memory, resulting in the loss of the now no-longer-referenceable memory to the system.

The Smart Pointer Pattern solves these problems by making the pointer itself an object. Because a Smart Pointer is an object, it can have constructors and destructors and operations that can ensure that its preconditional invariants ("rules of proper usage") are maintained.

6.5.2 Problem

In many ways, pointers are the bane of the programmer's existence. If they weren't so incredibly useful, we would have discarded them a long time ago. Because they allow us to dynamically allocate, deallocate, and reference memory dynamically, they form an important part of the programmer's toolkit. However, their use commonly results in a number of different kinds of defects.

  • Memory leaks—destroying a pointer before the memory they reference is released. This means that the memory block is never put back in the heap free store, so its loss is permanent, at least until the system is rebooted. Over time, the available memory in the heap free store (that is, memory that can now be allocated by request) shrinks, and eventually the system fails because it cannot satisfy memory requests.

  • Uninitialized pointer—using a pointer as if it was pointing to a valid object (or memory block) but neglecting to properly allocate the memory. This can also occur if the memory request is made but refused.

  • Dangling pointer—using a pointer as if it was pointing to a valid object (or memory block) but after the memory to which it points has been freed.

  • Pointer arithmetic defects—using a pointer as an iterator over an array of values but inappropriately. This can be because the pointer goes beyond the bounds of the array (in either direction), possibly stepping on memory allocated to other objects, or becoming misaligned, pointing into the middle of a value rather than at its beginning.

These problems arise because pointers are inherently stupid. They are only data values (addresses), and the operations defined on them are primitive and without checks on their correct use. If only they were objects, their operations could be extended to include validity checks and they could identify or prevent inappropriate use.

6.5.3 Pattern Structure

The basic solution of the Smart Pointer Pattern is to reify the pointer into an object. Once a pointer comes smart, or potentially smart, its operations can ensure that the preconditions of the pointer (it points to valid memory) are met. Figure 6-7a shows the simple structure of this pattern, and Figure 6-7b shows a common variant.

Figure 6-7Figure 6-7: Smart Pointer Pattern

6.5.4 Collaboration Roles

  • Client

    The Client is the object that at the analysis level simply has an association to the Target object. If this is a bidirectional association, then both these objects have smart pointers to the other.

  • Smart Pointer

    The Smart Pointer is an object that contains the actual pointer (rawPtr) as an attribute, as well as constructor, destructor, and access operations. The access operations will usually be realized by overriding pointer dereference operators ([] and ®) in C++, to hide the fact that a smart pointer is being used. The Target::referenceCount attribute keeps track of the number of smart pointers that are referring to the specific target object. It's important to know this so you can determine when to destroy the dynamically created Target.

    The Smart Pointer has two constructors. The default constructor creates a corresponding Target and sets referenceCount to the value 1. The second constructor initializes the rawPtr attribute to the value of the address passed in and increments the Target:: referenceCount. The destructor decrements the Target::reference-Count; if it decrements to 0; then the Target is destroyed. In principle, the Target::referenceCount must be referred to by all Smart Pointers that point to the same object.

  • Target

    The Target is the object providing the services that the Client wishes to access. In the basic form of the pattern (Figure 6-7a), Target also has a reference count attribute that tracks the number of Smart Pointers currently referencing it.

  • Target Wrapper

    In the Smart Pointer Pattern variant in Figure 6-7b, the Target object is not at all aware of Smart Pointers or reference counts. The Target Wrapper object contains via composition, the Target object, and it owns the referenceCount attribute.

6.5.5 Consequences

This is a mechanistic-level design pattern; that means it optimizes individual collaborations. The main advantage of applying this pattern is that it is a simple means to ensure that objects are destroyed when they are no longer accessible—that is, when all references to them have been (or are being) destroyed. This requires some discipline on the part of the programmers. If the Target object is being referenced by both smart and raw pointers, then this pattern will break with potential catastrophic consequences. On the other hand, using the pattern can be codified into an easily checked rule: Use no raw pointers; that is, validate during code reviews.

To ensure robustness in the presence of multithreaded access to an object (Smart Pointers exist in multiple threads that reference the same Target), then care must be taken in the creation of constructors and destructors. The simplest way to handle them is to make them atomic (prevent task switching during the construction or destruction of a Smart Pointer). You can do this easily by making the first operation in the constructor a call to the OS to prevent task switching (just don't forget to turn it back on when you're done!). The destructor must be similarly protected. Otherwise, there is a possibility that the object may be destroyed after you checked that it was valid and a Smart Pointer is now pointing to a Target that no longer exists. Finally, there is one situation in which Smart Pointers may be correctly implemented but still may result in memory leakage. The Smart Pointer logic ensures that whenever there is no Smart Pointer pointing to a Target, the Target will be deleted. However, it is possible to define small cycles of objects that contain Smart Pointers, but the entire cycle cannot be accessed by the rest of the application. In other words, it is still possible to get a memory leak if the collaboration of objects has cycles in it. Figure 6-8 shows how this can happen.

Figure 6-8Figure 6-8: Smart Pointer Cycles

Object Obj3 and Obj5 form a cycle. If Obj2 and Obj4 are destroyed, the reference counts associated with Obj3 and Obj5 decrement down to 1 rather than 0, and these two objects are unable to be referenced by the remainder of the application. Since their reference counts are greater than 1, they cannot be destroyed, but neither can the application invoke services of these objects because there are no references to these objects outside the cycle itself.

The easiest way to handle the problem is to ensure that no Target itself references another object that could ever reference the original. This can usually be deduced from drawing class diagrams of the collaborations and some object diagrams resulting from the execution of the class diagram. If cycles cannot be avoid, then it might be better to avoid using the Smart Pointer Pattern for those cycles specifically.

6.5.6 Implementation Strategies

This pattern is simple and straightforward to implement and should create no problems. If you desire a Smart Pointer Pattern that can handle cyclic object structures, then this can be solved at the cost of increased complexity and processing resource usage. A good discussion of these methods is provided in [2].

6.5.7 Related Patterns

There are more elaborate forms of the Smart Pointer in [2], although they are expressed as algorithms defined on the Smart Pointer rather than patterns per se, as it is here. When cycles are present but the benefits of the Smart Pointer Pattern (protection against pointer defects) are strongly desired, the Garbage Collector or Compacting Garbage Collector Patterns may be indicated.

6.5.8 Sample Model

Figure 6-9 shows a simple application of this pattern. Two clients of the HR Sensor object exist: one object that displays the values and another that tracks values to do trending analysis. When the HR Display object runs, it creates an HR Sensor object via a Wrapped Sensor object. The HR Display object also notifies the HR Trend object to begin tracking the heart rate information (via the Wrapped Sensor object).

Figure 6-9Figure 6-9: Smart Pointer Pattern Example

Later, the HR Display is destroyed. It calls the delete operation on the Wrapped Sensor class. The Wrapped Sensor decrements its reference count but does not delete the HR Sensor because the reference count is greater than zero (the HR Trend DB still has a valid reference to it). Later on, when the HR Trend DB removes the last pointer to the HR Sensor object, the HR Sensor object is finally deleted.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020