Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

C/C++

Counting Objects in C++


But here is the ambiguity problem. Which howMany should be made available by SpecialWidget, the one it inherits from Widget or the one it inherits from Counter<SpecialWidget>? The one we want, naturally, is the one from Counter<SpecialWidget>, but there's no way to say that without actually writing SpecialWidget::howMany. Fortunately, it's a simple inline function:

class SpecialWidget: public Widget,
    private Counter<SpecialWidget> {
public:
    .....
    static size_t howMany()
    { return Counter<SpecialWidget>::howMany(); }
    .....
};

The second observation about our use of inheritance to count objects is that the value returned from Widget::howMany includes not just the number of Widget objects, it includes also objects of classes derived from Widget. If the only class derived from Widget is SpecialWidget and there are five stand-alone Widget objects and three stand-alone SpecialWidgets, Widget::howMany will return eight. After all, construction of each SpecialWidget also entails construction of the base Widget part.

Summary

The following points are really all you need to remember:

  • Automating the counting of objects isn't hard, but it's not completely straightforward, either. Use of the "Do It For Me" pattern (Coplien's "curiously recurring template pattern") makes it possible to generate the correct number of counters. The use of private inheritance makes it possible to offer object-counting capabilities without increasing object sizes.
  • When clients have a choice between inheriting from an empty class or containing an object of such a class as a data member, inheritance is preferable, because it allows for more compact objects.
  • Because C++ endeavors to avoid memory leaks when construction fails for heap objects, code that requires access to operator new generally requires access to the corresponding operator delete too.
  • The Counter class template doesn't care whether you inherit from it or you contain an object of its type. It looks the same regardless. Hence, clients can freely choose inheritance or containment, even using different strategies in different parts of a single application or library.

Notes and References

[1] James O. Coplien. "The Column Without a Name: A Curiously Recurring Template Pattern," C++ Report, February 1995.

[2] An alternative is to omit Widget::howMany and make clients call Counter<Widget>::howMany directly. For the purposes of this article, however, we'll assume we want howMany to be part of the Widget interface.

[3] Scott Meyers. More Effective C++ (Addison-Wesley, 1996), pp. 113-122.

[4] Nathan Myers. "The Empty Member C++ Optimization," Dr. Dobb's Journal, August 1997. Also available at http://www.cantrip.org/emptyopt.html.

[5] Simple variations on this design make it possible for Widget to use Counter<Widget> to count objects without making the count available to Widget clients, not even by calling Counter<Widget>::howMany directly. Exercise for the reader with too much free time: come up with one or more such variations.

Further Reading

To learn more about the details of new and delete, read the columns by Dan Saks on the topic (CUJ January - July 1997), or Item 8 in my More Effective C++ (Addison-Wesley, 1996). For a broader examination of the object-counting problem, including how to limit the number of instantiations of a class, consult Item 26 of More Effective C++.

Acknowledgments

Mark Rodgers, Damien Watkins, Marco Dalla Gasperina, and Bobby Schmidt provided comments on drafts of this article. Their insights and suggestions improved it in several ways.


A Note About Placement new and Placement delete

The C++ equivalent of malloc is operator new, and the C++ equivalent of free is operator delete. Unlike malloc and free, however, operator new and operator delete are overloadable functions, and as such they may take different numbers and types of parameters. This has always been the case for operator new, but until relatively recently, it wasn't valid to overload operator delete.

The "normal" signature for operator new is:

void * operator new(size_t) throw (std::bad_alloc);

(To simplify things from now on, I'll omit exception specifications. They're not germane to the points I want to make.) Overloaded versions of operator new are limited to adding additional parameters, so an overloaded version of operator new might look like:

void * operator new(size_t, void *whereToPutObject)
{ return whereToPutObject; }

This particular version of operator new — the one taking an extra void* argument specifying what pointer the function should return — is so commonly useful that it's in the Standard C++ library (declared in the header <new>) and it has a name, "placement new." The name indicates its purpose: to allow programmers to specify where in memory an object should be created (where it should be placed).

Over time, the term placement new has come to be applied to any version of operator new taking additional arguments. (This terminology is actually enshrined in the grammar for C++ in the forthcoming International Standard.) Hence, when C++ programmers talk about the placement new function, they mean the function above, the one taking the extra void* parameter specifying where an object should be placed. When they talk about a placement new function, however, they mean any version of operator new taking more than the mandatory size_t argument. That includes the function above, but it also includes a plethora of operator new functions that take more or different parameter types.

In other words, when the topic is memory allocation functions, "placement new" means "a version of operator new taking extra arguments." The term can mean still other things in other contexts, but we don't need to go down that road here, so we won't. For details, consult the suggested reading at the end of the article.

By analogy with placement new, the term "placement delete" means "a version of operator delete taking extra arguments." The "normal" signature for operator delete is:

void operator delete(void*);

So any version of operator delete taking one or more arguments beyond the mandatory void* parameter is a placement delete function.

Let us now revisit an issue discussed in the main article. What happens when an exception is thrown during construction of a heap object? Consider again this simple example:

class ABCD { ... };
ABCD *p = new ABCD;

Suppose the attempt to create the ABCD object yields an exception. The main article pointed out that if that exception came from the ABCD constructor, operator delete would automatically be called to deallocate the memory allocated by operator new. But what if operator new is overloaded, and what if different versions of operator new (quite reasonably) allocate memory in different ways? How can operator delete know how to correctly deallocate the memory? Furthermore, what if the ABCD object being created used placement new, as in:

void *objectBuffer = getPointerToStaticBuffer();
ABCD *p = new (objectBuffer) ABCD; // create an ABCD object in a static buffer

(The) placement new didn't actually allocate any memory. It just returned the pointer to the static buffer that was passed to it in the first place. So there's no need for any deallocation.

Clearly, the actions to be taken in operator delete to undo the actions of its corresponding operator new depend on the version of operator new that was invoked to allocate the memory.

To make it possible for programmers to indicate how the actions of particular versions of operator new can be undone, the C++ Standards committee extended C++ to allow operator delete to be overloaded, too. When an exception is thrown from the constructor for a heap object, then, the game is played a special way. The version of operator delete that's called is the one whose extra parameter types correspond to those of the version of operator new that was invoked.

If there's no placement delete whose extra parameters correspond to the extra parameters of the placement new that was called, no operator delete is invoked at all. So the effects of operator new are not undone. For functions like (the) placement version of operator new, this is fine, because they don't really allocate memory. In general, however, if you create a custom placement version of operator new, you should also create the corresponding custom placement version of operator delete to go with it.

Alas, most compilers don't yet support placement delete. With code generated from such compilers, you almost always suffer a memory leak if an exception is thrown during construction of a heap object, because no attempt is made to deallocate the memory that was allocated before the constructor was invoked.


Scott Meyers authored the best-selling Effective C++, Second Edition and More Effective C++ (both published by Addison Wesley). Find out more about him, his books, his services, and his dog at http://www.aristeia.com.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.