auto_ptr vs unique_ptr

auto_ptr and unique_ptr

The new type std::unique_ptr is introduced in c++11, and supposed to be a replacement for std::auto_ptr.

But think this, if it is a direct replacement, why give it a new name rather than just improve the std::auto_ptr?

So let’s find about their differences:

  1. std::auto_ptr is copyable but std::unique_ptr can only be moved. Look at the following
// Anything like this
std::auto_ptr<int> p(new int);
std::auto_ptr<int> p2 = p; // Ownership transfered to p2

// will have to become at least like this
std::unique_ptr<int> p(new int);
std::unique_ptr<int> p2 = std::move(p);
  1. std::unique_ptr can handle arrays correctly (calling delete[]) while std::auto_ptr can not(calling delete).

The major flaw with std::auto_ptr is the implicit transfer of ownership. This statement is backed by the description here

conclusion

What’s the deal with auto_ptr? auto_ptr is most charitably characterized as a valiant attempt to create a unique_ptr before C++ had move semantics. auto_ptr is now deprecated, and should not be used in new code.

If you have auto_ptr in an existing code base, when you get a chance try doing a global search-and-replace of auto_ptr to unique_ptr; the vast majority of uses will work the same, and it might expose (as a compile-time error) or fix (silently) a bug or two you didn’t know you had.

你可能感兴趣的:(c/c++)