1

If I have a std::vector of std::unique_ptr and resize it, and wanted to add element by index, what is the best way to add them using operator=?

std::vector<std::unique_ptr<item>> _v;
_v.resize(100);
// is it safe to use the assignment operator? 
_v[20] = new item;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
devcodexyz
  • 65
  • 7
  • Do you think there are many ways to choose from? –  Oct 20 '17 at 18:47
  • most tutorial talk about using ways to use unique_ptr and ways to avoid just making sure there is no drawback with the = operator. – devcodexyz Oct 20 '17 at 18:52
  • 1
    Be careful with preceding underscores. They are often reserved for use by the library implementation. Handy reading: [What are the rules about using an underscore in a C++ identifier?](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier) – user4581301 Oct 20 '17 at 18:58
  • @MoradMohammad As mentioned in the answers, there is a drawback for using the assignment operator in a way that you show in your example: [it doesn't compile](https://ideone.com/7OXVw7). – Algirdas Preidžius Oct 20 '17 at 19:01

2 Answers2

1

std::unique_ptr does not have an assignment operator that takes a raw pointer.

But it does have an assignment operator that moves from another std::unique_ptr, which you can create using std::make_unique():

_v[20] = std::make_unique<item>();
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Chris Drew
  • 14,926
  • 3
  • 34
  • 54
  • 2
    Note that `std::make_unique()` was added in C++14. For C++11, you can use `_v[20] = std::unique_ptr(new item);` instead. – Remy Lebeau Oct 20 '17 at 18:51
1

You could use std::make_unique if you are using C++14, like that

_v[20] = std::make_unique<item>(/* Args */);

Otherwise if you are under C++14, you can make your own implementation of std::make_unique, or use the constructor of std::unique_ptr

_v[20] = std::unique_ptr<item>(new item(/* Args */));
bl4ckb0ne
  • 1,097
  • 2
  • 15
  • 30