-1

This is extracted from a more complicated example, but I'm wishing to keep a std::vector with unique_pointers to objects. I realize I need to move them in, but I can't seem to figure out how. Also, why can't I delete in the first example?

EDIT: I'm using strings just as an example. The pointed-to object will be a much larger struct.


// Works, but not what I want
std::string* rawJohnP = new(std::string) {"john"};
std::vector<std::string*> rawStringPtrVec {rawJohnP};
delete rawJohnP; // Fails to compile - why?


// how do I make a vector with jUnqPtr?
std::unique_ptr<std::string> jUnqPtr = std::make_unique<std::string>("john");
std::vector<std::unique_ptr<std::string>> stringPtrVec {std::move(jUnqPtr)}; // fails
stringPtrVec.emplace_back(std::move(jUnqPtr)); //fails
  • 1
    `stringPtrVec.emplace_back(std::move(jUnqPtr));` [works fine here](http://coliru.stacked-crooked.com/a/03a4c47f14dff2b6) – NathanOliver May 13 '22 at 19:46
  • 1
    `// Works, but not what I want` Doesn't work. `rawStringPtrVec` is left pointing to the `string` `delete rawJohnP;` wiped out of existence. – user4581301 May 13 '22 at 19:46
  • 3
    Initializing containers from braced lists always copies the elements, so yes, it won't work. `emplace_back` should work though. Also, why do you want `unique_ptr` instead of just `string`? – HolyBlackCat May 13 '22 at 19:48
  • 3
    Also, are you sure you want the elements of the vector to be `std::unique_ptr`? pointers to standard objects don't really give you anything and make the code more complicated. – NathanOliver May 13 '22 at 19:48
  • @NathanOliver@HolyBlackCat I'm only using std::string as an example. The pointed-to object will be a much larger struct. My code fails to compile on godbolt: https://godbolt.org/z/qd8ndWvbP :21:5: error: 'stringPtrVec' does not name a type 21 | stringPtrVec.emplace_back(std::move(jUnqPtr)); | ^~~~~~~~~~~~ Compiler returned: 1 – Bjorn Eriksson May 13 '22 at 20:33
  • @BjornEriksson It works if you put the code in a function: https://godbolt.org/z/P5sG5cxf5. You can't run arbitrary code outside of a function. – NathanOliver May 13 '22 at 20:38
  • Thanks @NathanOliver I just realized that was the issue. Really appreciate your help! – Bjorn Eriksson May 13 '22 at 20:43
  • @BjornEriksson If you are looking for a better initialization syntax, you can leverage the technique I use [here](https://stackoverflow.com/a/72004656/4342498) at the end of the answer to create a factory function to build the vector for you. – NathanOliver May 13 '22 at 20:47
  • You would use it like `auto stringPtrVec = make_vector(std::make_unique("john"), std::make_unique("mary"), std::make_unique("joseph")` – NathanOliver May 13 '22 at 20:48

0 Answers0