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...
asked May 19, 2015 at 11:32
Mendes
18.7k40 gold badges167 silver badges283 bronze badges
1 Answer 1
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);
answered May 19, 2015 at 11:34
TartanLlama
66.2k13 gold badges167 silver badges203 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-cpp
operator*to access the pointee, just like your plain old raw pointer.std::make_unique(as an alternative to your factory eg.)