Reputation: 2583
Is this a correct way of thinking about smart pointers and using raw pointers for non-ownership?
class DisplayObject {
DisplayObject* Parent;
};
class DisplayObjectContainer: public DisplayObject {
std::vector<DisplayObject*> Children;
};
class Stage {
std::vector<std::unique_ptr<DisplayObject>> DisplayObjects;
};
Items are created using
make_unique<DisplayObject>
or
make_unique<DisplayObjectContainer>
Stage would own all DisplayObject
classes but a DisplayObjectContainer
will have raw pointers to Stage's owned objects.
DisplayObject
will also have a Parent (which can be nullptr
).
I also take the Stage's DisplayObjects and get the pointer to it's object when I add the item to the vector (DisplayObjects.back().get()
) and make heavy use of std::move
Is this a correct way of using smart pointers and ownership?
Upvotes: 3
Views: 137
Reputation:
Looking at your code, yes. This looks like a perfectly good way to organize your code: you have a single class which is keeping explicit ownership, and every other class that uses raw pointers does not own what it is pointing at. This will keep your code clean, efficient, and everybody using it will know what breaks when, and how.
Just make sure if you do start to share this code around, you tell everyone upfront that raw pointers means it doesn't own resources, and that they are to not delete or new the resources themselves. Making this known upfront will prevent confusion on whether or not the pointers people use / pass to your methods need to be manually new'd.
Side note:
DisplayObject
? DisplayObjectContainer
? Sounds a lot like AS3's display hierarchy for C++! It sounds interesting. I wish you all the best.
Upvotes: 5