简体   繁体   中英

Usage of vector::emplace_back with shared_ptr

#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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM