c++unique-ptr

Can I allocate unique_ptr outside the function?


Is this correct? So can I allocate the dynamic var outside the function?

TMyClass* ClassA::myAllocFunc()
{
 return new MyClass;
}

void ClassA::myFunc()
{
 std::unique_ptr<MyClass> l(myAllocFunc);
 
}

Solution

  • Yes, you can have a function return a raw pointer and have std::unique_ptr take ownership of it.

    In your example, you just need to call the function and pass its return value to std::unique_ptr, not try to pass the function itself, eg:

    std::unique_ptr<MyClass> l(myAllocFunc()); // <-- notice the extra '()'
    

    That being said, a better option would be to have myAllocFunc() return a std::unique_ptr to begin with, not return a raw pointer, eg:

    std::unique_ptr<TMyClass> ClassA::myAllocFunc()
    {
        return std::make_unique<MyClass>();
    }
    
    void ClassA::myFunc()
    {
        std::unique_ptr<MyClass> l = myAllocFunc();
        // or simply:
        // auto l = myAllocFunc();
    }