mercredi 24 mars 2021

Passing std::unique_ptr to a function by using a variable that is already created using new X()

I am new to C++ and have some confusion regarding what happens in the following 2 scenarios.

  1. I create the variable using new key word and then pass that variable as std::unique_ptr<>(x) to a function. When I do this, I can still access this->handler_ from the class that I passed.

Note: Y is the super class of X


this->handler_ = new X(this);
auto res1 = root()->grpcStreamHandler(std::unique_ptr<Y>( this->handler_));

  1. Create the variable as a unique pointer and pass it directly.

Note: Y is the super class of X

this->handler_ = std::unique_ptr<Y>(new X(this));
auto res1 = root()->grpcStreamHandler(std::unique_ptr<Y>( std::move(handler_)));


For the 2nd case I know the std::move() moves the object and transfers the ownership to the function that we passed. But what's actually happening in the 1st case ? Would really appreciate if someone can explain clearly since I'm not very proficient in C++. Thanks

Aucun commentaire:

Enregistrer un commentaire