C++ – pass a unique_ptr’s reference to a function

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

Best Answer

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.