#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.
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.
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.
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.
emplace_back():This function can directly insert the object without calling the copy constructor.
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.
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