• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
larspensjo

std::vector vs std::unique_ptr

28 posts in this topic

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?
0

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

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].
0

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
0

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

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

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

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?
-1

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
0

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

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

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

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

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!
2

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
1

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
0

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?
0

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 ;)
1

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
0

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
0

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 ;-)
0

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]
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0