I have an object of class A
created inside a method. This method also creates an instance of an object B
that takes as constructor argument the object A
just created. B
has to take the ownership of the object A
but it can't modify it. This means that A
should be deleted when B
is deleted, but during the lifetime of B
it cannot modify A
.
In this case a std::unique_ptr<const A>
as a member variable of B
is the right way to transfer the ownership of A
(using std::move
in the constructor of B
) and guarantee that it won't be modified?
Yes, that's precisely the semantics you're looking for. std::unique_ptr<T>
states "I own the T
object." A pointer (raw or smart) to const A
states "I cannot modify the A
to which I point." Taken together, it's exactly what you're after.
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