Ownership talks about how is responsible about the lifetime of the object.
Let say you have a class shape
that on which you can do various actions like, calculating the surface area, enlarging or shrinking that object, ...
And those tasks are performed by free functions calculate_shape_area
, enlarge_shape
, shrink_shape
, and you pass the shape to that function, then those functions don't require ownership over that object, they only need to know the object while they are called. So you can (and should) pass that object as raw pointer:
struct shape {};
double calculate_shape_area(shape* obj) {
// calculate the area, obj is only used within that function
// and not stored anywhere else
}
int main() {
auto obj = std::make_unique<shape>();
auto area = calculate_shape_area(obj.get());
}
If you, on the other hand, want to store that shape in a scene graph using insert
and that scenegraph, at a later step, displays all shapes. Then the scenegraph needs to know about that object after the call of insert
so it either needs to create a copy of it or needs to claim ownership over it. And if you don't want to create a copy then you either need to move a unique_ptr
to that insert
or use shared_ptr
.