Home > front end >  How to convert a raw pointer to unique_ptr?
How to convert a raw pointer to unique_ptr?

Time:08-24

I have this sample code:

std::unique_ptr<Base> some_function() {
    //I cannot use unique ptr here becuase it will get freed when the function return i guess
    Derived* derived = new Derived;
    return static_cast<std::unique_ptr<Base>>(derived);
}

Is using static_cast here is a good solution? Are there other alternatives to return unique_ptr?

And

return std::unique_ptr<Command>(derived);

if I return like this, will the ptr be freed at the end of the return expression since it is anynomous?

And what is the workaround if I don't want to use raw pointers in Derived* derived = new Derived;?

CodePudding user response:

I cannot use unique ptr here becuase it will get freed when the function return i guess

You can simply return it and the ownership of the raw pointer stored in the smart pointer will be transferred from your local variable to the std::unique_ptr<Base>.

std::unique_ptr<Base> some_function() {
    auto derived = std::make_unique<Derived>();

    // use derived in here ...

    return derived; // and return it by value
}

Demo

  • Related