How to pass unique pointer to function in c++ ?
Source code:
/* Program: Unique pointer pass to function Author: Alpha Master Date: 23 September 2021 */ //Header File #include<iostream> #include<memory> #include<string> std::unique_ptr<std::string> addSuffix(std::unique_ptr<std::string> upt) { std::string temp = (*upt.get()) + " master"; std::cout<<temp<<std::endl; //reset upt.reset(new std::string(temp)); return upt; } void addSuffix01(std::unique_ptr<std::string>& upt) { std::string temp = (*upt.get()) + " digestcpp.com"; std::cout<<temp<<std::endl; //reset upt.reset(new std::string(temp)); return; } int main() { std::cout<<"Unique pointer"<<std::endl; //Creat new object std::unique_ptr<std::string> up { new std::string {"alpha"}}; //pass this unique object to function via value std::unique_ptr<std::string> out = addSuffix(std::move(up)); std::cout<<"Output:"<<*out.get(); std::cout<<std::endl; //pass this unique object to function via actual object addSuffix01(out); std::cout<<"Output:"<<*out.get(); std::cout<<std::endl; return 0; }
Output:
Unique pointer alpha master Output:alpha master alpha master digestcpp.com Output:alpha master digestcpp.com