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);
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With