SmartPointerQ: It appears that std::auto_ptr can do everything that boost::scoped_ptr can do. So why did Boost bother to provide this class. According to a boost list posting from Beman Dawes [message]:
The primary reason to use scoped_ptr rather than auto_ptr is to let readers of your code know that you intend "resource acquisition is initialization" to be applied only for the current scope, and have no intent to transfer ownership.
A (very) secondary reason to use scoped_ptr is to prevent a later maintenance programmer from adding a function that actually transfers ownership by returning the auto_ptr (because the maintenance programmer saw auto_ptr, and assumed ownership could safely be transferred.)
Think of bool vs int. We all know that under the covers bool is usually just an int. Indeed, some argued against including bool in the standard because of that. But by coding bool rather than int, you tell your readers what your intent is. Same with scoped_ptr - you are signalling intent."
In essence, boost::scoped_ptr is similar to std::auto_ptr const, but it more clearly shows that transfer of ownership is NOT allowed. -- RG
Please pardon my complete lack of expertise on this subject, but I thought one of the main reasons to use scoped_ptr and shared_ptr is that they are safe(r) to use inside STL container classes. No?
No. But why not just try it and see if it compiles? You'll find that scoped_ptr cannot be used in a container because it is not assignable and copyable. shared_ptr is fine in containers.
class X {
// ...
X(const X& other) : my_scoped_ptr(new X(*other.my_scoped_ptr)) { }
X& operator=(const X& other) { *my_scoped_ptr = *other.my_scoped_ptr; }
void swap(X& other) { std::swap(*my_scoped_ptr, *other.my_scoped_ptr); }
};
It would be nice to also provide an implementation of a reference counted pointer with the intrusive model, i.e. the reference counted class must derive from a specific base class that contains the counter. Especially since it was shown somewhere else on this web site that it is the most efficient smart pointer implementation.
-- MB
It would be interesting to also have a class of RC'ed smart ptrs with COW semantics, where non-const access would call a required clone() method to get the copy.
-- MB