Reputation: 372
I'm wondering why make_unique calls copy constructor but does not call default constructor.
Node()
{
std::cout << "default";
}
~Node(){
std::cout << " Delete";
}
Node(const Node& other ){
std::cout << "copy";
}
int main(){
Node<int,int,int,int> test1; //Calling default Cons
std::unique_ptr<Node<int,int,int,int>> test2 =
std::make_unique<Node<int,int,int,int>>(test1);//Nothing called
Node<int,int,int,int> *test3 = test2.get();
Node<int,int,int,int> test4 = Node<int,int,int,int>(*test3);// Calling copy Cons
std::unique_ptr<Node<int,int,int,int>> test5 =
std::make_unique<Node<int,int,int,int>(test4);//Calling copy Cons
}
For example in code shown above: Frist, we create Node object -> calling default constructor. Then we wrap this object into smart-pointer object -> no calls.
But if we make deep copy of Node object -> calling copy constructor And then wrap copy into smart-pointer object-> calling copy constructor.
It's somehow connected to the creation of new control block?
Upvotes: 4
Views: 7707
Reputation: 11158
std::unique_ptr<Node<int,int,int,int>> test5 =
std::make_unique<Node<int,int,int,int>(test4);// You copy from test4
std::make_unique
creates a new pointer. It doesn't reuse an existing pointer.
So since test4 is already there, it has to copy it. After test5 is constructed, test4 is still there (so can't do a move) and test5 is holding a new object, copied from test4.
Upvotes: 6