Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass a unique_ptr's reference to a function?

Tags:

c++

Can I pass a unique_ptr's reference to a function? If not why should I avoid it?

Ex:

void func(unique_ptr<Clss>& ref);

main() {
   unique_ptr<Clss> a = std::make_unique<Clss>();
   fn(a);
}
like image 876
Nujufas Avatar asked Dec 11 '22 07:12

Nujufas


1 Answers

Can I pass a unique_ptr's reference to a function?

Yes, a unique_ptr is class like any other.

You should do this when you want to mutate an existing unique_ptr from a function (e.g. calling .reset() on it).

If only you want to access the object inside unique_ptr<T>, take T& or const T& in your function interfaces, so that they can be used independently of unique_ptr.

like image 62
Vittorio Romeo Avatar answered Dec 29 '22 02:12

Vittorio Romeo