Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unique_ptr to transfer ownership of a const object

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?

like image 513
gcswoosh Avatar asked Mar 13 '15 13:03

gcswoosh


1 Answers

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.

like image 141
Angew is no longer proud of SO Avatar answered Nov 20 '22 01:11

Angew is no longer proud of SO