user2856064 user2856064 - 1 year ago 59
Linux Question

What is the difference between *ptr and *ptr.get() when using auto_ptr?

Why would I use

, instead of just calling

Consider the following code:

auto_ptr<int> p (new int);
*p = 100;
cout << "p points to " << *p << '\n'; //100

auto_ptr<int> p (new int);
*p.get() = 100;
cout << "p points to " << *p.get() << '\n'; //100

Result is exactly the same. Is
more secure?

Answer Source

Practically no difference.

In case of *p, the overloaded operator* (defined by auto_ptr) is invoked which returns the reference to the underlying object (after dereferencing it — which is done by the member function). In the latter case, however, p.get() returns the underlying pointer which you dereference yourself.

I hope that answers your question. Now I'd advise you to avoid using std::auto_ptr, as it is badly designed — it has even been deprecated, in preference to other smart pointers such as std::unique_ptr and std::shared_ptr (along with std::weak_ptr).