Jump to content

  • Log In with Google      Sign In   
  • Create Account


std::vector vs std::unique_ptr


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
28 replies to this topic

#1 larspensjo   Members   -  Reputation: 1526

Like
0Likes
Like

Posted 28 June 2012 - 06:06 AM

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
  • is better to use when you want to transfer ownership
  • has no overhead (memory or CPU)
std::vector:
  • is better when the initial size is unknown as it allows for dynamic growth
  • keeps track of the size for you
Am I missing something?
Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

Sponsor:

#2 Rattenhirn   Crossbones+   -  Reputation: 1658

Like
4Likes
Like

Posted 28 June 2012 - 06:51 AM

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.

#3 Emmanuel Deloget   Members   -  Reputation: 1381

Like
0Likes
Like

Posted 28 June 2012 - 09:36 AM

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<> is a smart pointer for arrays. There is no need for anything else.

#4 Zoomulator   Members   -  Reputation: 269

Like
3Likes
Like

Posted 28 June 2012 - 10:30 AM

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, 28 June 2012 - 10:31 AM.


#5 Cornstalks   Crossbones+   -  Reputation: 6966

Like
0Likes
Like

Posted 28 June 2012 - 11:08 AM

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

You are correct.
[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#6 larspensjo   Members   -  Reputation: 1526

Like
0Likes
Like

Posted 28 June 2012 - 11:23 AM

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:

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


Edited by larspensjo, 28 June 2012 - 11:30 AM.

Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

#7 larspensjo   Members   -  Reputation: 1526

Like
0Likes
Like

Posted 28 June 2012 - 11:43 AM

First of all, the title of this message is very misleading.

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?

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.

I don't understand this. A vector is a one dimensional array. So for the one dimensional case, there are no differences by definition.
Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

#8 e‍dd   Members   -  Reputation: 2105

Like
2Likes
Like

Posted 28 June 2012 - 11:58 AM

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.

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

#9 Bregma   Crossbones+   -  Reputation: 4748

Like
0Likes
Like

Posted 28 June 2012 - 12:24 PM

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.
Stephen M. Webb
Professional Free Software Developer

#10 larspensjo   Members   -  Reputation: 1526

Like
-1Likes
Like

Posted 28 June 2012 - 03:39 PM

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?
Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

#11 jonathanjansson   Members   -  Reputation: 271

Like
0Likes
Like

Posted 28 June 2012 - 04:19 PM

[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, 28 June 2012 - 04:33 PM.


#12 Cornstalks   Crossbones+   -  Reputation: 6966

Like
1Likes
Like

Posted 28 June 2012 - 07:55 PM

Is it allowed to use &v[0], where v is a std::vector?

Yes, that is legal.

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?

That would certainly be an important consideration, and possibly a determining factor.
[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#13 Codarki   Members   -  Reputation: 462

Like
1Likes
Like

Posted 29 June 2012 - 02:21 AM

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

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.

#14 Bregma   Crossbones+   -  Reputation: 4748

Like
1Likes
Like

Posted 29 June 2012 - 05:53 AM

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 is not only allowed, it is considered idiomatic.

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?

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.
Stephen M. Webb
Professional Free Software Developer

#15 larspensjo   Members   -  Reputation: 1526

Like
0Likes
Like

Posted 29 June 2012 - 06:50 AM

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.

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.
Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

#16 Rattenhirn   Crossbones+   -  Reputation: 1658

Like
2Likes
Like

Posted 29 June 2012 - 09:50 AM

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?


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.

I don't understand this. A vector is a one dimensional array. So for the one dimensional case, there are no differences by definition.


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!

#17 Zoomulator   Members   -  Reputation: 269

Like
1Likes
Like

Posted 29 June 2012 - 04:12 PM

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 is not only allowed, it is considered idiomatic.

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, 29 June 2012 - 04:14 PM.


#18 Matt-D   Crossbones+   -  Reputation: 1410

Like
0Likes
Like

Posted 01 July 2012 - 08:07 PM

Since in C++11 std::unique_ptr replaced Boost's boost::scoped_ptr /* http://stackoverflow...aking-ownership */, you might as well compare with boost::scoped_array: http://www.boost.org...coped_array.htm

For some discussion(s), see:
http://www.progtown....std-vector.html
http://www.gamedev.n...s-scoped_array/
http://www.tebyan.ne...x=22&Language=3
http://lists.boost.o...1/10/187258.php

Edited by Matt-D, 01 July 2012 - 08:16 PM.


#19 iMalc   Crossbones+   -  Reputation: 2258

Like
0Likes
Like

Posted 02 July 2012 - 12:42 AM

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.

More importantly, it works when the vector is empty too!

So nobody mentioned std::array yet huh?
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

#20 Zoomulator   Members   -  Reputation: 269

Like
1Likes
Like

Posted 02 July 2012 - 07:03 AM

So nobody mentioned std::array yet huh?


Pfft, I did. Fourth post ;)




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS