shared_pointer and persistancy


#1

Hi there,

I have got an issue with shared pointers used by chaiscript, I want to use shaiscript to allow user to populate a scene graph. So I exposed the method to add a node inside a group like :

class MyGroup
{
[...]
public:
  void AddNode(MyNode* node)
  {
    childs_.push_back(node);
  }
  std::vector<MyNode*>  childs_;
[...]
};

The problem is when I close the console (and delete shaiscript engine) all shared pointers are erased and my scene graph contains deleted node, so it crashes…
how can I force to increment reference count to be increased or bypass this issue ?

edit : I think using a factory will solve my issue, is there any other solution ?

Thank you


#2

maybe i’m missing something, but if that AddNode accepts plain pointers, i wouldn’t expect it to increase reference count. i think that if you want to keep those nodes around, you’ll have to actually use shared_pointers in MyGroup too. or not use them at all in that context so script-side pointers don’t delete automagically.


#3

The example is a very simplified version, in fact my scene graph implementation is more complex and I don’t want to modify this part of the code.


#4

Are nodes created by pure scripted functions, or are you calling a C++ func to create nodes for you? I guess if you allocate those nodes “yourself”,chaiscript won’t feel responsible for those and won’t delete them.


#5

Yes that was I meant by “using a factory”, I will do that.

Thank


#6

So, I believe I understand.

  1. You are creating the objects inside of ChaiScript, so there is 1 reference to them: inside of the script engine.
  2. You pass the objects to your node structure, which only takes a pointer, so as @ninnghazad pointed out, there’s no reference count increase.
  3. You destroy the ChaiScript engine, which pops the only reference count from the stack and the nodes are destroyed

Someone needs to keep ownership of those nodes. You could do it with a factory as you suggest, or you could share the nodes with ChaiScript/C++, something like:

C++ land

std::vector<Boxed_Value> nodes;
chai.add(var(&nodes), "nodes")

ChaiScript land

var n = Node();
group.AddNode(n);
nodes.push_back(n);

now this nodes object will extend the lifetime of any object pushed into it for the entire life of the std::vector<Boxed_Value> that is shared between ChaiScript and C++.

-Jason