Are there any advantages of using std::unique_ptr<T>& instead of std::unique_ptr<T>?

  • A+
Category:Languages

Are there any advantages of using std::unique_ptr<T>& instead of std::unique_ptr<T>? For example, in function arguments?

 


std::unique_ptr can only be moved so if you pass unique_ptr by value then you cannot extract its contents after function call but if you pass by reference then value can be retrieved. Below is sample code for the same :

#include <iostream> #include <memory> void changeUniquePtrReference(std::unique_ptr<int>& upr) {     *upr = 9;    } void changeUniquePtrValue(std::unique_ptr<int> upv) {     *upv = 10; } int main() {   std::unique_ptr<int> p(new int);   *p =8;   std::cout<<"value of p is "<<*p<<std::endl;   changeUniquePtrReference(p);   std::cout<<"value of p is "<<*p<<std::endl;   changeUniquePtrValue(std::move(p));   std::cout<<"Memory deallocated so below line will crash.. "<<std::endl;   std::cout<<"value of p is "<<*p<<std::endl;    return 0; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: