• Advertisement
Sign in to follow this  

std::vector vs std::unique_ptr

This topic is 2027 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to understand the changes and differences with some of the smart pointers and containers. Using the vector form of std::unique_ptr<T[]> has some overlapping functionality with std::vector. What are the general guidelines here? What I think, is:

std::unique_ptr[list]
[*]is better to use when you want to transfer ownership
[*]has no overhead (memory or CPU)
[/list]
std::vector:[list]
[*]is better when the initial size is unknown as it allows for dynamic growth
[*]keeps track of the size for you
[/list]
Am I missing something?

Share this post


Link to post
Share on other sites
Advertisement
First of all, the title of this message is very misleading.

What you actually want to know is the difference between an array which life time is managed with unique_ptr vs. std::vector.

Fortunately there is a good general guideline:
Use std::vector!

If you need to know why, please search for some of the discussion about arrays vs. vector and remove all arguments against arrays that concern lifetime management of the array's memory.

Share this post


Link to post
Share on other sites
I concur.

Thou shall never manage arrays through anything but std::vector<>.

For one, the std::default_deleter (that you don't want to change, otherwise you manager a std::unique_ptr<T,Deleter> instead of a std::unique_ptr<T>) performs a delete on the underlying object, while you'll want a delete[].

Second, std::vector<> [i]is[/i] a smart pointer for arrays. There is no need for anything else.

Share this post


Link to post
Share on other sites
I'm pretty sure the default deleter does a delete[] on array unique_ptr's. The template is specialized for array types.

Anyway, transferring ownership is pretty easy with a vector too. If you return a vector created in the same function, it'll actually trigger the move semantics, resulting in only the pointer to the contents being moved to the new vector "copy" outside the function. That means the move takes constant time no matter how big a vector.

To force move semantics, you use the std::move function. This effectively transfers ownership the same way.

Only difference is that the unique_ptr enforces the ownership a bit more by not being implicitly copyable.

Very few occations call for a C array (with or without unique_ptr), and if you actually need a constant sized container, use the new std::array rather than a C-array. The std::array can be entirely stack allocated as well since it's constant sized, which is pretty handy at times. Edited by Zoomulator

Share this post


Link to post
Share on other sites
[quote name='Zoomulator' timestamp='1340901034' post='4953700']
I'm pretty sure the default deleter does a delete[] on array unique_ptr's. The template is specialized for array types.
[/quote]
[url="http://msdn.microsoft.com/en-us/library/ee410601.aspx"]You are correct[/url].

Share this post


Link to post
Share on other sites
Thanks for some feed-back, but there is still no explanation on why I should use std::vector instead of std::unique_ptr for managing vectors.

If that is the case, then there is the question why there is a std::unique_ptr for managing vectors?

Edit: Well, there is one argument (and some added facts) from Zoomulator: [quote][left][background=rgb(250, 251, 252)]Only difference is that the unique_ptr enforces the ownership a bit more by not being implicitly copyable.[/quote][/background][/left] Edited by larspensjo

Share this post


Link to post
Share on other sites
[quote name='Rattenhirn' timestamp='1340887909' post='4953646']
First of all, the title of this message is very misleading.[/quote]
Please explain in what way it is misleading? std::vector is used to manage vectors. std::unique_ptr is used to manage pointers to objects or vectors. So it is rather obvious what I was asking for, isn't it?

[quote]Fortunately there is a good general guideline:
Use std::vector!

If you need to know why, please search for some of the discussion about arrays vs. vector and remove all arguments against arrays that concern lifetime management of the array's memory.
[/quote]
I don't understand this. A vector is a one dimensional array. So for the one dimensional case, there are no differences by definition.

Share this post


Link to post
Share on other sites
[quote name='larspensjo' timestamp='1340904216' post='4953711']
Thanks for some feed-back, but there is still no explanation on why I should use std::vector instead of std::unique_ptr for managing vectors.[/quote][list]
[*]You have a size(). With a unique_ptr<T[]> you have to keep a size along side it
[*]You have a richer interface. T[] doesn't give you a whole lot out the box.
[*]You can add/remove elements after you've decided the initial array size
[*]std::vector can be moved/swapped if need be.
[*]std::vector can be copied
[/list]
In fact, there really isn't much overlap between std::vector and unique_ptr<T[]> besides the indexing operator.

Does unique_ptr<T[]> support construction from an initializer list? If not, there's another important difference.

Share this post


Link to post
Share on other sites
A vector is a first-class object. The contiguous memory handled by a unique_ptr is not. A vector has copy semantics by default, a unique_ptr has move semantics by default. It's all the difference in the world, even if they both just deal with ways to access dynamically-allocated contiguous regions of memory.

Share this post


Link to post
Share on other sites
So, it looks like std::vector supports everything I can do with std::unique_ptr<T[]>, and more. And you usually want to keep size information for a vector, anyway.

I tested with a function that defined a local std::vector, initialized it, and then returned it. Initializing a variable with the result of this function did indeed reference the same memory area, which means there was an implicit move. I wonder how that works (though it did what I wanted). Anyway, I get the ownership defined, automatic memory management, and the source/sink functionality to work.

One use-case I have, is to create a vector of data that need to be temporarily forwarded externally (in this case a vertex attribute list forwarded to an OpenGL VBO). Using std::unique_ptr, I can use the get() function to get a pointer. Is it allowed to use &v[0], where v is a std::vector?

It seems to me then that the advantage of std::unique_ptr (compared to std::vector) is when you want to ensure it is not copied?

Share this post


Link to post
Share on other sites
[Edit] I didn't read the other replies careful enough and managed to repeat a lot of information except how to change the deleter!

[Edit] Actually I removed my answer completely because it is wrong to change the deleter. std::unique_ptr<int[]> selects the corret deleter already. Listen to Edd! Edited by jonathanjansson

Share this post


Link to post
Share on other sites
[quote name='larspensjo' timestamp='1340919565' post='4953767']
Is it allowed to use &v[0], where v is a std::vector?
[/quote]
Yes, that is legal.

[quote name='larspensjo' timestamp='1340919565' post='4953767']
It seems to me then that the advantage of std::unique_ptr (compared to std::vector) is when you want to ensure it is not copied?
[/quote]
That would certainly be an important consideration, and possibly a determining factor.

Share this post


Link to post
Share on other sites
[quote name='larspensjo' timestamp='1340919565' post='4953767']
I tested with a function that defined a local std::vector, initialized it, and then returned it. Initializing a variable with the result of this function did indeed reference the same memory area, which means there was an implicit move. I wonder how that works (though it did what I wanted).
[/quote]
First, initializing a variable with the result of a function calls the move constructor, which std::vector has.
Second, if the object doesn't have move constructor, RVO (return value optimization) is probably performed by the compiler.

Share this post


Link to post
Share on other sites
[quote name='larspensjo' timestamp='1340919565' post='4953767']One use-case I have, is to create a vector of data that need to be temporarily forwarded externally (in this case a vertex attribute list forwarded to an OpenGL VBO). Using std::unique_ptr, I can use the get() function to get a pointer. Is it allowed to use &v[0], where v is a std::vector?[/quote]
It is not only allowed, it is considered idiomatic.
[quote]It seems to me then that the advantage of std::unique_ptr (compared to std::vector) is when you want to ensure it is not copied?[/quote]
A big advantage of using a vector is that you're dealing with a first-class object. It tells the reader "I have a buffer and I'm using it to hold data". Using any kind of pointer instead and you tell the read "I have an address to some memory somewhere, and I'm using that address to do stuff indirectly to that memory". Turns out in the world of professional software development, much more time is spent in maintenance than in development. Being able to communicate intent as clearly as possible is the mark of the best code. the more you can work in the problem domain rather than the implementation domain, the clearer your intent tends to be.

Share this post


Link to post
Share on other sites
[quote name='Bregma' timestamp='1340970812' post='4953931']
Turns out in the world of professional software development, much more time is spent in maintenance than in development. Being able to communicate intent as clearly as possible is the mark of the best code. the more you can work in the problem domain rather than the implementation domain, the clearer your intent tends to be.
[/quote]
I certainly appreciate that, having used Google Go rather than C++ a couple of years now. So far, my productivity has been about 3 times as high with Go as with C++. Proper use of smart pointers and containers in C++ is an important step towards that goal.

Share this post


Link to post
Share on other sites
[quote name='larspensjo' timestamp='1340905391' post='4953720']
Please explain in what way it is misleading? std::vector is used to manage vectors. std::unique_ptr is used to manage pointers to objects or vectors. So it is rather obvious what I was asking for, isn't it?[/quote]

The title of this thread is "std::vector vs std::unique_ptr". I'm pretty sure most people started to read it, because they were wondering how one could possibly meaningfully compare those two and not because they want to discuss vector vs. array, which has been discussed to death already.

[quote name='larspensjo' timestamp='1340905391' post='4953720']I don't understand this. A vector is a one dimensional array. So for the one dimensional case, there are no differences by definition.[/quote]

In your original post you asked "What are the general guidelines here?" for "std::vector vs std::unique_ptr" (to a T[]).
I gave you a general guideline, that is very simple and very effective.

If you look at vector vs. array from the perspective, that both of them store a sequence of values in a continuous chunk of memory, then yes, there is no difference. However, there are differences between "std::vector vs std::unique_ptr" (to a T[]), which is, if I understood you at all, what you asked for. And the answer is that vector is preferable in pretty much every case, because it offers more functionality and safer interface, at the cost of approximately 2 extra pointers.


If you're so starved on memory, that you can't afford those 2 extra pointers, you'll need to stay away from allocations on the free-store anyways, so unique_ptr to a T[] is no help either.

I hope that clarifies things!

Share this post


Link to post
Share on other sites
[quote name='Bregma' timestamp='1340970812' post='4953931']
[quote name='larspensjo' timestamp='1340919565' post='4953767']One use-case I have, is to create a vector of data that need to be temporarily forwarded externally (in this case a vertex attribute list forwarded to an OpenGL VBO). Using std::unique_ptr, I can use the get() function to get a pointer. Is it allowed to use &v[0], where v is a std::vector?[/quote]
It is not only allowed, it is considered idiomatic.
[/quote]
In C++11 this can now be replaced with the data() method, which returns a pointer to the first value just like &v[0], but with a bit clearer intent. It's also a const pointer, which &v[0] doesn't provide. Edited by Zoomulator

Share this post


Link to post
Share on other sites
Since in C++11 std::unique_ptr replaced Boost's boost::scoped_ptr /* [url="http://stackoverflow.com/questions/3019512/c0x-unique-ptr-replaces-scoped-ptr-taking-ownership"]http://stackoverflow...aking-ownership[/url] */, you might as well compare with boost::scoped_array: [url="http://www.boost.org/doc/libs/release/libs/smart_ptr/scoped_array.htm"]http://www.boost.org...coped_array.htm[/url]

For some discussion(s), see:
[url="http://www.progtown.com/topic73400-boost-scopedarray-vs-std-vector.html"]http://www.progtown....std-vector.html[/url]
[url="http://www.gamedev.net/topic/327741-c-boosts-scoped_array/"]http://www.gamedev.n...s-scoped_array/[/url]
[url="http://www.tebyan.net/newindex.aspx?pid=31159&BookID=22053&PageIndex=22&Language=3"]http://www.tebyan.ne...x=22&Language=3[/url]
[url="http://lists.boost.org/Archives/boost/2011/10/187258.php"]http://lists.boost.o...1/10/187258.php[/url] Edited by Matt-D

Share this post


Link to post
Share on other sites
[quote name='Zoomulator' timestamp='1341007944' post='4954116']
In C++11 this can now be replaced with the data() method, which returns a pointer to the first value just like &v[0], but with a bit clearer intent. It's also a const pointer, which &v[0] doesn't provide.
[/quote]More importantly, it works when the vector is empty too!

So nobody mentioned std::array yet huh?

Share this post


Link to post
Share on other sites
[quote name='iMalc' timestamp='1341211351' post='4954802']
So nobody mentioned std::array yet huh?
[/quote]

Pfft, I did. Fourth post ;)

Share this post


Link to post
Share on other sites
Oh, so you did. Nobody responded about it though. Oh well.

Share this post


Link to post
Share on other sites
I am using unique_ptr<x[]> whenever I want to read large arrays directly from binary files. It skips vector's default-initialization of the allocated memory and allows efficient use of istream::read instead of per-element-read operations.

Does anyone know a way to get these advantages (maybe there are even specific compiler optimizations for this case?) by using a vector instead of unique_ptr<x[]>?

Cheers, rnlf

Share this post


Link to post
Share on other sites
I'm not sure if you can bypass the default initialization, but &myvector[0] (or better myvector.data() on C++11) points to the exact same block of memory you can use for istream::reads. Edited by BitMaster

Share this post


Link to post
Share on other sites
Yes, I know that. But for large chunks of memory (like large textures, vertex or audio data) I would like to circumvent the initialization. I think, using a unique_ptr ist reasonably secure and it is also quite convenient, since the size of the block is always known beforehand and will never be resized.

i just thought, maybe someone knows a way to get the best out of both worlds ;-)

Share this post


Link to post
Share on other sites
I keep it simple and just use [font=courier new,courier,monospace]char*[/font] along with simply disallowing transfer/modification of the buffer's initial lifetime (which is assigned to a scope-stack)... that's probably not the most popular C++-esque answer, but it works for me, is dead simple and pretty hard to screw up [img]http://public.gamedev.net//public/style_emoticons/default/tongue.png[/img]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement