I would like to know the difference between 'std::unique_ptr' and 'std::auto_ptr' from C++11. I think the two of you use the same method, but what's the difference exactly?

Asked 1 years ago, Updated 1 years ago, 81 views

I would like to know the difference between std::unique_ptr and std::auto_ptr that occurred from C++11. I think the two of you use the same method, but what's the difference exactly?

c++ c++11

2022-09-21 18:29

1 Answers

Most of the time, they do the same thing. However, the difference is that auto_ptr can be copied, while unique_ptr can only be moved.

What it means is that auto_ptr is

std::auto_ptr<int> p(new int);
std::auto_ptr<int> p2 = p; 

It is possible, but unique_ptr is not possible. To mimic the above code with unique_ptr

std::unique_ptr<int> p(new int);
std::unique_ptr<int> p2 = std::move(p);

We have to share.

Another difference is that unique_ptr handles the array better. auto_ptr calls delete, but unique_ptr calls delete[].


2022-09-21 18:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.