Mendes
Mendes

Reputation: 18441

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...

Upvotes: 1

Views: 144

Answers (1)

TartanLlama
TartanLlama

Reputation: 65600

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

Upvotes: 3

Related Questions