jeudi 3 décembre 2015

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

Aucun commentaire:

Enregistrer un commentaire