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.
make_shared is exception-safe. It uses the same call to allocate the memory for the control block and the resource, which reduces the construction overhead. If you don't use make_shared , then you have to use an explicit new expression to create the object before you pass it to the shared_ptr constructor.
std::make_sharedAllocates and constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr<T> that owns and stores a pointer to it (with a use count of 1). This function uses ::new to allocate storage for the object.
You could let in-place move construction to occur:
vec.emplace_back(std::make_shared<int>(42));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With