Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique_ptr<int[]> or vector<int>?

If you don't need dynamic growth and don't know the size of the buffer at compile time, when should unique_ptr<int[]> be used instead of vector<int> if at all?

Is there a significant performance loss in using vector instead of unique_ptr?

like image 824
huitlarc Avatar asked Aug 27 '13 17:08

huitlarc


People also ask

What is a unique_ptr in C++?

(since C++11) std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

When should we use unique_ptr?

Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.

Does unique_ptr call destructor?

Yes. Well the unique ptr has a function object that by default invokes delete on the pointed to object, which calls the destructor. You can change the type of that default deleter to do almost anything.


1 Answers

There is no performance loss in using std::vector vs. std::unique_ptr<int[]>. The alternatives are not exactly equivalent though, since the vector could be grown and the pointer cannot (this can be and advantage or a disadvantage, did the vector grow by mistake?)

There are other differences, like the fact that the values will be initialized in the std::vector, but they won't be if you new the array (unless you use value-initialization...).

At the end of the day, I personally would opt for std::vector<>, but I still code in C++03 without std::unique_ptr.

like image 70
David Rodríguez - dribeas Avatar answered Oct 04 '22 01:10

David Rodríguez - dribeas