auto_ptr VS shared_ptr

auto_ptr and shared_ptr solve entirely different problems. One does not replace the other.

auto_ptr is a thin wrapper around pointers to implement RAII semantics, so that resources are always released, even when facing exceptions. suto_ptr does not perform any reference counting or the like at all, it does not make multiple pointers point to the same object when creating copies. In fact, it's very different. auto_ptr is one of the few classes where the assignment operator modifies the source object.
Consider this shameless plug from the auto_ptr wikipedia page:

int *i = new int;
auto_ptr x(i);
auto_ptr y;

y = x;
cout <cout << y.get() <
Note how executing

y = x;
modifies not only y but also x.

The boost::shared_ptr template makes it easy to handle multiple pointers to the same object, ans the object is only deleted after the last reference to it went out of scope. this feature is not ssueful in you scenario, which (attempts to) implement a Singleton. In the Singleton scenario, there's always either o references to 1 reference to the only object of the class, if any.

In essence, auto_ptr objects and shared_ptr objects have entirely different semantics (that's why you cannot use the former in containers, but doing so with the latter is fine).

No comments:

Post a Comment