Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 437
user2856064 Avatar asked Dec 02 '22 14:12

user2856064


2 Answers

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).

like image 51
Nawaz Avatar answered Dec 23 '22 01:12

Nawaz


*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.

like image 41
rgmt Avatar answered Dec 23 '22 01:12

rgmt