Saturday, February 8, 2014

c++ smart pointer class example

c++ smart pointer class example : Standard Template Library Tutorial, ccplusplus.com

Implementing Reference Semantics

In general, STL container classes provide value semantics and not reference semantics. Thus, they create internal copies of the elements they contain and return copies of those elements. To summarize, if you want reference semantics in STL containers (whether because copying elements is expensive or because identical elements will be shared by different collections), you should use a smart pointer class that avoids possible errors. Here is one possible solution to the problem. It uses an auxiliary smart pointer class that enables reference counting for the objects to which the pointers refer:



This class resembles the standard auto_ptr class. It expects that the values with which the smart pointers are initialized are return values of operator new. However, unlike auto_ptr, it allows you to copy these smart pointers while retaining the validity of the original and the copy. Only if the last smart pointer to the object gets destroyed does the value to which it refers get deleted.

You could improve the class to allow automatic type conversions or the ability to transfer the ownership away from the smart pointers to the caller.

The following program demonstrates how to use this class:


The program has the following output:


Note that if you call an auxiliary function that saves one element of the collections (an IntPtr) somewhere else, the value to which it refers stays valid even if the collections get destroyed or all of their elements are removed.








-----------------------------------------------------------------
See Also:
-----------------------------------------------------------------

-----------------------------------------------------------------

No comments:

Post a Comment