c++ 传递 unique_ptr 作为对另一个函数的引用

c++ Passing unique_ptr as a reference to another function

这看起来很基础,但我需要一些帮助。

我有样品class:

class myClass {
   int a;
   int b;

}

然后是工厂:

class myFactory {
    std::unique_ptr<myClass> getInstance()
    {
        return std::unique_ptr<myClass>(new myClass);
    }
}

然后我有几个函数将通过引用接收 myClass

doSomething (myClass& instance)
{
    instance.a = 1;
    instance.b = 2;
}

还有 main 代码,我卡在了这里:

main()
{
    myFactory factory;
    std::unique_ptr<myClass> instance = factory.getInstance();

    doSomething(instance.get()) <--- This is not compiling
}

如何正确调用 doSomething() 函数,按预期传递实例作为参考?

注意doSomething()会修改实例数据...

std::unique_ptr<T>::get returns 底层原始指针,而不是指针对象。 unique_ptr 提供 operator* 直接获取实例。

doSomething(*instance);