Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a raw pointer to unique_ptr?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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;?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading