[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!
Show differencesHistory of post edits
#2jonathanjansson
Posted 28 June 2012 - 04:26 PM
std::vector is used to manage vectors. std::unique_ptr is used to manage pointers to objects or vectors.
The wording is a bit confusing but I think I understand. Avoid writing this:
std::unique_ptr<int> x(new int[1000]);
because
- The memory will be deleted with delete instead of delete []
- It is weird to index the array like this: x.get()[index]
- The unique_ptr don't know the size of the array
- The array can't grow
std::unique_ptr<int, std::default_delete<int[]> x(new int[1000]);
But you should really use std::vector instead because it works like a container and not a pointer.
[Edit] I didn't read the other replies careful enough and managed to repeat a lot of information except how to change the deleter!
#1jonathanjansson
Posted 28 June 2012 - 04:19 PM
std::vector is used to manage vectors. std::unique_ptr is used to manage pointers to objects or vectors.
The wording is a bit confusing but I think I understand. Avoid writing this:
std::unique_ptr<int> x(new int[1000]);
because
- The memory will be deleted with delete instead of delete []
- It is weird to index the array like this: x.get()[index]
- The unique_ptr don't know the size of the array
- The array can't grow
std::unique_ptr<int, std::default_delete<int[]> x(new int[1000]);
But you should really use std::vector instead because it works like a container and not a pointer.