26

I was trying to find some easy way to emplace elements in a std::vector<std::shared_ptr<int>> but couldn't come with anything. std::shared_ptr takes pointers as parameters, so I can still write this:

std::vector<std::shared_ptr<int>> vec;
vec.emplace_back(new int(10));

However, I don't want to use new by hand if possible, and would rather like to use std::make_shared if possible. The problem is that if I really want to use it, I have to use push_back instead and lose the advantage of in-place construction:

std::vector<std::shared_ptr<int>> vec;
vec.push_back(std::make_shared<int>(10));

Is there any way to get the advantages of both emplace_back and std::make_shared? If not, is there a guideline I should follow in such a case?

EDIT: Actually, I asked this question, but had an unrelated problem. Andy's answer is the good one and there isn't any actual problem with using both emplace functions and std::make_shared at once.

Morwenn
  • 21,684
  • 12
  • 93
  • 152

1 Answers1

28

You could let in-place move construction to occur:

vec.emplace_back(std::make_shared<int>(42));
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
  • Didn't he just say he couldn't do that? – David G May 21 '13 at 23:34
  • 1
    @0x499602D2 Don't worry, that was just me being dumb and forgetting about the template parameter in `make_shared` when I first tried it. Actually, my question was as dumb as possible, everybody should just forget about it. I unintentionally asked a question about a problem when I had another one. – Morwenn May 21 '13 at 23:39
  • 14
    @Morwenn: This solution is indeed functionnal, but I would suspect it to be equivalent to a push_back, with the drawback of being less explicit. `emplace`family of methods are originally intended for in-place construction of values, without copy nor moves (cf. [std::queue::emplace(...)](http://en.cppreference.com/w/cpp/container/queue/emplace)), allowing to avoid the creation of a temporary. When you actually want to copy construct from a temporary (what is happening here), I think `push` family of methods are the canonical way of doing things. Anyway, the compiler could (or not) elide copies. – Ad N Nov 12 '13 at 10:28