This is my first time experiencing smart pointers in c++ and i have some understanding issues.
I want to design some kind of a Component Based OpenGL framework.
So I have a Scene class which creates Nodes ( and stores the for itself ) and return it as a shared_ptr.
Node class has a list of Components which are created in Node class and again returned as a shared_ptr BUT these Components also need a reference to their owner (Node) and the Node itself should pass its pointer to its Components.
Now: the pointer to the Node in its components, what should it be? a shared_ptr or a weak_ptr. and how to pass that wthitin the Node itself ( Node has no reference to its shared_ptr which is stored in the Scene )
//! EDIT 1
class Scene
{
vector<shared_ptr<Node>> nodes;
public:
weak_ptr<Node> NewNode();
}
class Node
{
vector<shared_ptr<Component>> components;
public:
weak_ptr<Component> AddComponent();
weak_ptr<Component> GetComponent(String classname);
vecotr<weak_ptr<Component>> GetComponents(String classname);
}
class Component
{
weak_ptr<Node> owner;
Component(weak_ptr<Node> owner_refernce);
public:
// component stuff
weak_ptr<Node> GetOwner();
friend class Node;
}
Please help me to make the best design here.
// EDIT1 : to be more clear!
Scene is the only OWNER of a Node. It creates and destroys them.
Each Node OWNS all of its Components. It creates and destroys them.
And the Components need a reference to their Owners which they will share with other objects ( by returning the owner in Get method ).
-> Scene owns Nodes and Nodes own Component.
-> Scene shares Nodes ( return Node object by name )
-> Node shared all its Components ( return Component by classname )
-> Components share their owner ( return owner reference )
How can i share Objects without sharing the ownership? weak_ptr ??
EDIT 2: It seems smart pointers are no use in this case. so I am going with raw pointers for now
From your description, it sounds like
Nodeinstances havea clear owner (
Scene). If so,shared_ptrisn’t necessarilythe best solution;
std::unique_ptr, or even raw pointers (withthe necessary deletes in
~Scene) would probably be moreappropriate. Or perhaps Boost’s pointer vector. The same
considerations apply to
ComponentandNode. And the parentpointers in
Componentlook like they’re strictly fornavigation, so raw pointers would be the most appropriate.