3

I have a std::unique_ptr<T> object and a library function that takes T& as a parameter. This function will change T object data.

What is the better way to pass the std::unique_ptr<T> to that function ? Is the above code correct ? Is there a better approach ?

#include <iostream>
#include <string>
#include <memory>

class Test {

   public: 
       std::string message = "Hi";
};

void doSomething(Test& item)
{
    item.message = "Bye";
}

int main()
{
     std::unique_ptr<Test> unique = std::unique_ptr<Test>(new Test());

     std::cout << unique->message << " John." << std::endl;

     doSomething(*unique.get());

     std::cout << unique->message << " John." << std::endl;
}
1
  • 5
    *unique is enough. Commented Dec 3, 2015 at 10:37

2 Answers 2

11

You don't need to call get, just dereference:

doSomething(*unique);

It is best to pass around references to the stored object rather than passing the std::unique_ptr around by reference, as the lifetime and storage of an object shouldn't need to be communicated to every function using that object.

Sign up to request clarification or add additional context in comments.

Comments

6

The standard library smart pointers are supposed to be used like raw pointers when it comes to dereferencing the pointer. That is, you'd simply use

std::unique_ptr<Test> unique(new Test());
std::cout << unique->message << " John.\n";
doSomething(*unique);

I included the declaration to show the simplified use and one output to emphasize not to use std::endl.

Comments

Your Answer

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.