Mendes
Mendes

Reputation: 18541

C++ Correct way to pass a std::unique_ptr object as reference on a function argument

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

Upvotes: 3

Views: 1146

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154025

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.

Upvotes: 6

TartanLlama
TartanLlama

Reputation: 65770

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.

Upvotes: 11

Related Questions