Question

In boost::scoped_ptr, says "It supplies a basic "resource acquisition is initialization" facility, without shared-ownership or transfer-of-ownership semantics." It is done through some non-copyable mechanism.

My question is why is there requirement for no shared-ownership?

Here is what I mean:

 template <typename T>
 class my_scoped_ptr
 {
 public:
  // constructor  implemented not shown here
  // operator*() implemented not shown here
  // operator -> implemented not shown here
  ~my_scoped_ptr()
  {
   delete my_p;
   my_p = NULL;
  }
 private:
  T * my_p;
 };


 void foo()
 {
  my_scoped_ptr<someclass> p (new someclass());
  my_scoped_ptr<someclass> q (p); // both p & q point to same my_p object
  // may be an exception is raised
 }

Ok now , regardless whether or not exception is raised the my_p will be deleted. so, when the code get out of foo's scope ...my_scope_ptr p destructor is called, deleting my_p and setting my_p to null. Now my_scope_ptr q destructor is called again deleting my_p , which is null at this point. It seems at destruction time I could care less whether a remaining copied pointer is pointing to a valid object.

So, why would I need to care that my_scoped_ptr should not be copyable? I don't see any harm of a ptr being copyable, if the ptr takes care of deleting the object pointed to , once it exits the scope. ??!!

Was it helpful?

Solution

void foo()
 {
  my_scoped_ptr<someclass> p (new someclass());
  my_scoped_ptr<someclass> q (p); // both p & q point to same my_p object
  // may be an exception is raised
 }

As the function ends (return or throw) and q goes out of scope, the destructor for q will delete the someclass object. Then immediately afterward, p goes out of scope and its destructor will delete the someclass object again.

It is not valid to delete the same pointer twice! (unless new happened to return it again in the meantime).

[ And if any C++ implementation tried to make it valid, it would either have to link together all raw pointers with the same value (which is what shared_ptr is for), or else keep track of what addresses have been deleted, which means they're still using memory of some sort and not really freed up. ]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top