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:
-----------------------------------------------------------------
See Also:
-----------------------------------------------------------------
See Also:
-----------------------------------------------------------------
- Complete Tutorial of C++ Template's
- Standard Template Library Tutorial
- Inter Process Communication Tutorial
- Advance Programming in C & C++
-----------------------------------------------------------------
No comments:
Post a Comment