Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of vector::emplace_back with shared_ptr

Tags:

c++

#include <iostream>
#include <vector>
#include <memory>
using namespace std;

struct BinaryTree
{
    int element;    
    shared_ptr<BinaryTree> left;
    shared_ptr<BinaryTree> right;
};

int main()
{
   vector<shared_ptr<BinaryTree>> vecBT;

   // case I
   vecBT.emplace_back(new BinaryTree{10, nullptr, nullptr});

   // case II
   vecBT.emplace_back(shared_ptr<BinaryTree>(new BinaryTree{20, nullptr, nullptr}));

   return 0;
}

http://en.cppreference.com/w/cpp/container/vector/emplace_back
template< class... Args >
void emplace_back( Args&&... args );

http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr
template< class Y >
explicit shared_ptr( Y* ptr );

Question> I have compiled the above code through http://www.compileonline.com/compile_cpp11_online.php without error.

My question is how the case I can pass the compiler without generating errors. Since constructor of shared_ptr requires explicit construction. So I expect only case II is correct.

like image 388
q0987 Avatar asked Nov 06 '13 20:11

q0987


People also ask

What does vector Emplace_back do?

The C++ function std::vector::emplace_back() inserts new element at the end of vector. Reallocation happens if there is need of more space. This method increases container size by one.

When should I use Emplace_back?

Specific use case for emplace_back : If you need to create a temporary object which will then be pushed into a container, use emplace_back instead of push_back . It will create the object in-place within the container.

Should I use Emplace_back or Push_back?

You should definitely use emplace_back when you need its particular set of skills — for example, emplace_back is your only option when dealing with a deque<mutex> or other non-movable type — but push_back is the appropriate default. One reason is that emplace_back is more work for the compiler.

Does Emplace_back call constructor?

emplace_back():This function can directly insert the object without calling the copy constructor.


1 Answers

Both cases are correct, the constructor of std::shared_ptr is explicit, but that is exactly what is called from emplace_back which is just forwarding its arguments to the explicit constructor call. That's different from taking a std::shared_ptr as an argument and requesting an implicit conversion.

like image 112
Daniel Frey Avatar answered Sep 18 '22 17:09

Daniel Frey