somenath <
somen...@gmail.com> wrote in
news:1b336c7c-f523-4bd8...@googlegroups.com:
> class ListItem {
> public:
> ListItem( T Val );
> shared_ptr <ListItem > Next;
> T Data;
>
> };
[...]
> Also I am not able to get convinced the benefit of shared_ptr and
> unique_ptr in the context of my code. I could have used even raw
> pointers to implement the same without losing much benefit . Is it not
> the case here?
Shared pointers are useful when you need to refer to the same object from
different places and you don't have good or natural control over the
lifetime of the object otherwise. So, using them in an implementation
*inside* of a list of items is pretty pointless, as you have noticed
yourself.
A need to refer to the same object from different places in this way
arises only if these are so-called entity objects (maintaining a changing
state) or they are too expensive or too large to copy casually. In both
cases the copy ctor and assignment operator should be absent or at least
not readily accessible, which is in direct violation with your code where
T objects are passed and held by value and copied all over the place.
> Please point me to some real code where smart pointers has been
> heavily used.
Our codebase uses them extensively, but the code is proprietary, sorry.
Mostly it is about maintaining data items in a script language
interpreter.
But take any look of some Windows C++ code using COM (or whatever it is
called this year). The COM objects are reference counted and disposed
when the last reference drops. There is a _com_ptr_t class template
which is used for defining smartpointers, starting from IUnknownPtr and
up to things like MSHTML::IHTMLDocument2Ptr. Any C++ code should use
those smartpointers for accessing COM interfaces (it is possible to do it
the hard C way as well, but this is error-prone, especially when mixed
with C++ exceptions).
Cheers
Paavo