Home > Articles > Programming > C/C++

Smart Pointers

We haven't talked yet about the most common type of resource—an object allocated using operator new and afterwards accessed through a pointer. Should we, for each type of object, define a separate encapsulator class? (As a matter of fact, the C++ standard library already has a template class, called the auto_ptr, whose purpose is to provide such encapsulation. I'll come back to auto_ptr later.) Let's start with something very inflexible but foolproof. Look at this smart pointer template—it's so rigid it can't even be instantiated:

template <class T>
class SPtr
{
public:
  ~SPtr () { delete _p; }
  T * operator->() { return _p; }
  T const * operator->() const { return _p; }
protected:
  SPtr (): _p (0) {}
  explicit SPtr (T* p): _p (p) {}
  T * _p;
};

Why did I make the constructors of SPtr protected? I had to, if I wanted to follow the first rule of acquisition. The resource—in this case an object of class T—must be allocated in the constructor of the encapsulator. But I can't simply call new T, because I have no idea what arguments the constructor of T requires. Since, in principle, each T has a different constructor; I need to define a different encapsulator for it. Having a template helps a lot. For each new class, I can define a new encapsulator that inherits the entire behavior from the appropriate SPtr and simply provides a specialized constructor:

class SItem: public SPtr<Item>
{
public:
  explicit SItem (int i)
  : SPtr<Item> (new Item (i)) {}
};

Is creating a new smart pointer class for each type really worth the effort? Frankly—no! It has a great pedagogical value, but once you've learned how to follow the first rule of acquisition, you can relax it and start using the advanced technique. The technique is to make the constructor of SPtr public, but use it only for direct resource transfer. By that I mean to use the result of the operator new directly as an argument to the constructor of SPtr, like this:

SPtr<Item> item (new Item (i));

This method obviously requires more self-control, not only from you but also from every member of your programming team. They have to swear not to use this public constructor for any other purpose but direct resource transfer. Fortunately, this rule is easy to enforce. Just grep the sources from time to time for all occurrences of new.

Resource Transfer

So far we've been talking about resources whose lifetimes could be limited to a single scope. Now it's time to tackle the difficult problem—how to safely transfer resources between scopes. The problem is most clearly visible when you're dealing with containers. You can dynamically create a bunch of objects, store them in a container, then later retrieve them, use them, and eventually dispose of them. For this to work safely—with no leaks—objects have to change owners.

The obvious solution is to use smart pointers, both before adding objects to the container and after retrieving them. This is how it goes. You add the Release method to the smart pointer:

template <class T>
T * SPtr<T>::Release ()
{
  T * pTmp = _p;
  _p = 0;
  return pTmp;
}

Notice that after Release is called, the smart pointer is no longer the owner of the object—its internal pointer is null.

Now, whoever calls Release must be a very responsible person and immediately stash the returned pointer into some other owner object. In our case, it's the container that calls Release, as in this Stack example:

void Stack::Push (SPtr <Item> & item) throw (char *)
{
  if (_top == maxStack)
    throw "Stack overflow";
  _arr [_top++] = item.Release ();
};

Again, you can enforce the responsible use of Release—you can grep for it in your sources.

What should the corresponding Pop method do? Should it release the resource and pray that whoever calls it be a responsible person and immediately make a direct resource transfer into a smart pointer? That just doesn't sound right.

Strong Pointers

Resource management worked in the Content Index (part of Windows NT Server and now part of the Windows 2000 operating system), and I was pretty satisfied with it. Then I started thinking... This methodology forms such a complete system, wouldn't it be really nice to have support for it built directly into the language? I came up with the idea of strong and weak pointers. A strong pointer would be a lot like our SPtr—it would destroy the object it pointed to when going out of scope. Resource transfer would occur as a result of simple assignment of strong pointers. There would also be weak pointers, used for accessing objects without owning them—sort of like assignable references.

Any pointer could be declared either strong or weak and the language would take care of type conversion rules. For instance, you could not pass a weak pointer where a strong pointer was expected, but the opposite would be legal. The Push method would accept a strong pointer and transfer its resource to the stack's array of strong pointers. The Pop method would return a strong pointer, so the client would have to assign it to another strong pointer. The introduction of strong pointers into the language would make garbage-collection history.

There is only one small problem—modifying the C++ standard is as easy as running for President of the United States. When I mentioned my idea to Bjarne Stroustrup, he looked at me as if I just asked him to lend me a thousand dollars.

Then a sudden idea struck me. I can implement strong pointers myself. After all, they're just like smart pointers. It's not a big problem to provide them with a copy constructor and an overloaded assignment operator. In fact, this is what the standard library auto_ptr's have. It's important to give the resource-transfer semantics to these operations, but that's also easy:

template <class T>
SPtr<T>::SPtr (SPtr<T> & ptr)
{
  _p = ptr.Release ();
}

template <class T>
void SPtr<T>::operator = (SPtr<T> & ptr)
{
  if (_p != ptr._p)
  {
    delete _p;
    _p = ptr.Release ();
  }
}

What made the whole idea suddenly click was the realization that I could pass such encapsulated pointers by value! I had my cake and could eat it too. Look at the new implementation of Stack:

class Stack
{
  enum { maxStack = 3 };
public:
  Stack ()
  : _top (0)
  {}
  void Push (SPtr<Item> & item) throw (char *)
  {
    if (_top >= maxStack)
      throw "Stack overflow";
    _arr [_top++] = item;
  }
  SPtr<Item> Pop ()
  {
    if (_top == 0)
      return SPtr<Item> ();
    return _arr [--_top];
  }
private
  int _top;
  SPtr<Item> _arr [maxStack];
};

The Pop method forces the client to assign its result to a strong pointer, SPtr<Item>. An attempt to assign it to a regular pointer will result in a compiler error, because the types don't match. Moreover, since Pop returns a strong pointer by value (there is no ampersand after SPtr<Item> in the declaration of Pop), the compiler performs a resource transfer for us in the return statement. It calls operator= to acquire an Item from the array, and the copy constructor to pass it to the caller. The caller ends up owning the Item through the strong pointer to which he or she has assigned the result of Pop.

I immediately knew I was onto something. I started rewriting my code using the new approach.

Parser

I had an old parser of arithmetic operations that was written using old resource management techniques. A parser is a producer of nodes that form a parsing tree. These nodes are dynamically allocated. For instance, the Expression method of the parser produces an expression node. It took me no time to rewrite the parser using strong pointers. I made the methods Expression, Term, and Factor return strong pointers to Nodes, and return them by value. Look at the implementation of the Expression method:

SPtr<Node> Parser::Expression()
{
  // Parse a term
  SPtr<Node> pNode = Term ();
  EToken token = _scanner.Token();
  if ( token == tPlus || token == tMinus )
  {
    // Expr := Term { ('+' | '-') Term }
    SPtr<MultiNode> pMultiNode = new SumNode (pNode);
    do
    {
      _scanner.Accept();
      SPtr<Node> pRight = Term ();
      pMultiNode->AddChild (pRight, (token == tPlus));
      token = _scanner.Token();
    } while (token == tPlus || token == tMinus);
    pNode = up_cast<Node, MultiNode> (pMultiNode);
  }
  // otherwise Expr := Term
  return pNode; // by value!
}

First, the method Term is called. It returns a strong pointer to Node by value and we immediately store it in our own strong pointer, pNode. If the next token is not the plus or the minus sign, we simply return this SPtr by value, thus releasing the ownership of the Node to the caller. On the other hand, if the token is either plus or minus, we create a new SumNode and immediately (direct transfer) store it in a strong pointer to MultiNode. Here SumNode derives from MultiNode, which derives from Node. The ownership of the original Node is passed to the SumNode.

We keep creating terms as long as they're separated by plus or minus signs. We transfer these terms to our MultiNode, which takes over their ownership. Finally, we up-cast the strong-pointer-to-MultiNode to the strong-pointer-to-Node and return it to the caller.

We need to do the explicit up-casting of strong pointers even though the pointers they encapsulate can be implicitly converted. For instance, a MultiNode is-a Node, but the same is-a relationship doesn't hold between SPtr<MultiNode> and SPtr<Node> because they're separate classes (instantiations of the template) that don't inherit from each other. The up_cast template is defined as follows:

template<class To, class From>
inline SPtr<To> up_cast (SPtr<From> & from)
{
  return SPtr<To> (from.Release ());
}

If your compiler supports member templates, the newest addition to C++ standard, you can instead define a template constructor for SPtr<T> that takes a strong pointer to another class U:

template <class T>
template <class U>   SPtr<T>::SPtr (SPrt<U> & uptr)
  : _p (uptr.Release ())
{}

The trick here is that this template will not compile if U is not a subclass of T (in other words, it will only compile if U is-a T). That's because uptr.Release () returns a pointer to U, which is then assigned to _p, which is a pointer to T. So if U is not a T, this assignment will result in a compile-time error.

std::auto_ptr

Then I realized that the template auto_ptr, that was added to the standard library, was nothing else but my strong pointer. At that time there were still some implementation differences (the release method of auto_ptr didn't zero the internal pointer—your compiler's library might in fact still contain this obsolete implementation), but they were resolved at the last moment, before the standard was officially accepted.

Transfer Semantics

So far I've been describing a methodology for managing resources in a C++ program. The idea was to keep all resources encapsulated in lightweight objects that would be responsible for their release. In particular, all resources allocated using the operator new could be stored and passed inside strong pointers (the Standard Library auto_ptr).

The key word here is passing. A container can safely release a resource by returning a strong pointer by value. The client of the container can receive such a resource only by providing an appropriate strong pointer to store it. Any attempt to assign the result to a naked pointer will be detected immediately by the compiler:

auto_ptr<Item> item = stack.Pop (); // ok
Item * p = stack.Pop (); // Error! Type mismatch.

Objects that are passed by value are said to have value semantics or copy semantics. Strong pointers are passed by value—but can we say they have copy semantics? Not really! The objects they point to are definitely not being copied. In fact, after the transfer, the source auto_ptr no longer has access to the original object and the target auto_ptr becomes its sole owner. (The old implementation of auto_ptr used to retain access to the object even after releasing its ownership.) It makes perfect sense to call this new behavior transfer semantics.

The copy constructor and the assignment operator that define the auto_ptr's transfer semantics take non-const references to auto_ptr as their arguments:

auto_ptr (auto_ptr<T> & ptr);
auto_ptr & operator = (auto_ptr<T> & ptr);

This is because they do modify their sources—they take away the ownership of the resources.

By defining an appropriate copy constructor and overloading the assignment operator, you can add transfer semantics to a variety of objects. For instance, a lot of resources in Windows, such as dynamically created menus or bitmaps, can be encapsulated in classes with transfer semantics.

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