Std :: unique_ptr to transfer ownership of a const object

I have a class A object created inside a method. This method also creates an instance of object B , which takes the newly created object A as a constructor argument. B must take responsibility for object A , but he cannot change it. This means that A should be deleted when B is removed, but during the life of B it cannot change A

In this case, a std::unique_ptr<const A> as a member variable of B is the right way to transfer ownership of A (using std::move in constructor B ) and ensure that it will not be changed?

+5
source share
1 answer

Yes, this is the semantics you are looking for. std::unique_ptr<T> indicates that I have a T object. A pointer (raw or smart) to const A indicates: "I cannot change the A that I am pointing to." Taken together, this is exactly what you need.

+8
source

Source: https://habr.com/ru/post/1215296/


All Articles