Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make_shared and emplace functions

Tags:

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.

like image 757
Morwenn Avatar asked May 21 '13 23:05

Morwenn


People also ask

What is the use of Make_shared?

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.

What is Make_shared in CPP?

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.


1 Answers

You could let in-place move construction to occur:

vec.emplace_back(std::make_shared<int>(42)); 
like image 174
Andy Prowl Avatar answered Sep 18 '22 18:09

Andy Prowl