On 03-May-17 4:58 AM, fl wrote:
>
> I have the below code snippet from "C++ Primer" 4th edition. It is seen that
> ip is deleted inside the destructor, but 'use' has no such deletion.
> I don't find the reason on the web. I see pointer ip is the same with 'use'
> on memory usage here.
>
> Could you tell me that?
`delete ip;` does the following:
If `ip` is not a nullpointer, then
{
1. Destroy the object that `ip` points to
For an `int` pointee this is a no-op, but for an object of class
type it generally involves executing that object's destructor.
2. Deallocate the memory that the object occupied.
This is like cancelling a reservation of seats in a cinema or plane.
It lets others reserve and use those seats. Or memory block.
}
These actions do not make sense for an `int`, only for a pointer.
> Thanks a lot
>
>
> ////////////////////
> /* smart pointer class: takes ownership of the dynamically allocated
> * object to which it is bound
> * User code must dynamically allocate an object to initialize a HasPtr
> * and must not delete that object; the HasPtr class will delete it
> */
> //private class for use by HasPtr only
> class U_Ptr {
> friend class HasPtr;
> int *ip;
> size_t use;
> U_Ptr(int *p): ip(p), use(1) { }
> ~U_Ptr() { delete ip; }
> };
This code is ungood in many ways:
• It's not a good idea to allocate an `int` dynamically. The overhead of
dynamic allocation is extreme compared to basic operations like `int`
assignment. Copying an `int` has nearly zero cost.
• It's a DIY solution where `std::shared_ptr` or `std::unique_ptr` would
be extremely much more appropriate.
• It fails to take charge of copying.
• The names do not indicate the purpose of anything.
• Everything `private` with `HasPtr` class as a friend, indicates that
this should be part of `HasPtr`, a nested `struct` there.
But regarding the last point, rather this class should not exist at all:
one should use a standard library smart pointer unless it can't do the
job. And if a standard library smart pointer was used, instead of this
class, that would still be wrong-ish because single `int` values simply
should not be dynamically allocated.
Cheers & hth.,
- Alf