Why would I use get() with *, 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 get() more secure?
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).
*p calls auto_ptr::operator*, which dereferences the managed pointer.
*p.get first calls method auto_ptr::get, which returns the managed pointer, which is then dereferenced by operator *.
These will provide exactly the same result once executed: the managed pointer is dereferenced, and there will be no additional checking when using get.
Note that auto_ptr is deprecated since C++11. It is dangerous because ownership of the pointer is transfered when copying:
std::auto_ptr<int> p(new int(42));
{
std::auto_ptr<int> copy_of_p(p); // ownership of *p is transfered here
} // copy_of_p is destroyed, and deletes its owned pointer
// p is now a dangling pointer
To avoid the problem, you had to "manage the managed pointers":
std::auto_ptr<int> p(new int(42));
{
std::auto_ptr<int> copy_of_p(p); // ownership of *p is transfered here
// ...
p = copy_of_p; // p gets back ownership
} // copy_of_p is destroyed, but doesn't delete pointer owned by p
// p is still valid
Use unique_ptr or shared_ptr instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With