1

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
3
  • get() returns a pointer, your function takes a reference. Commented May 19, 2015 at 11:34
  • 2
    operator* to access the pointee, just like your plain old raw pointer. Commented May 19, 2015 at 11:36
  • you might be interested in std::make_unique (as an alternative to your factory eg.) Commented May 19, 2015 at 11:38

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.