简体   繁体   中英

c++ Passing unique_ptr as a reference to another function

This seens to be basic, but I need some help.

I have a sample class:

class myClass {
   int a;
   int b;

}

Then a factory:

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

Then I have several funtions that will receive myClass by reference:

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

And the main code, where I´m stuck:

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

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

How do I correctly call the doSomething() function passing the instance as a reference as expected ?

Note that doSomething() will modify instance data...

std::unique_ptr<T>::get returns the underlying raw pointer, not the pointee. unique_ptr provides operator* for directly getting at the instance.

doSomething(*instance);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM