Incorrect ValueTree Usage

Hi all. Another ValueTree question from me. I have created a class to setup a value tree full of properties to control OSC messages being sent, return the value tree that it creates and write the values to an xml file. This class gets used in the ‘top level’ application class as a scoped pointer, a class for buffering OSC messages as a scoped pointer and then in a window containing tabs of TreeViews also as a scoped pointer.

My problem is that none of these trees all reference the same value, so I end up with 7 trees all acting independently. This has lead me to believe that I am using ValueTrees in completely the wrong way (and/ or my application design wasn’t too good!). Can somebody give me a quick run down of their correct usage/ where I’m going wrong?

Source code can be found here for anybody interested:

TL;DR can you give a pointer, where the code is that you struggle with? It’s quite some code in the linked repository :wink:

My bad, I was in such a rush making the post I forgot to show the problem!
This link is the class I am using to handle the ValueTree.

The problem occurs when the following if is true (line 30 in the gist)

else if (treeExists == true)
    myoMapperGlobalData = new ValueTree (getValueTree());

I know that this will never work as getValueTree returns a pointer to myoMapperGlobalData. Without including the top-level application file in this class, how can I ensure that they are all referencing the same valueTree or how can I make it so changing one tree causes the same changes in the others?

Ideally you shouldn’t create the ValueTree on the heap. Rather use it by value.
The docs say:

Create ValueTree objects on the stack, and don’t be afraid to copy them around, as they’re simply a lightweight reference to a shared data container. Creating a copy of another ValueTree simply creates a new reference to the same underlying object - to make a separate, deep copy of a tree you should explicitly call createCopy().

Hopefully by changing this you can get rid of the problem.


Aaahhhh, completely missed that! What’s the ‘standard’ way to go about deleting the object and any references to it then to prevent leaking?

You can simply assign it. To clear it completely, just assign it to an invalid one:

ValueTree tree1 = ValueTree ("test");
ValueTree tree2 = tree1;
tree2.setProperty ("foo", "bar", nullptr);
// both should have the property

tree2 = tree1.createCopy();
tree2.setProperty ("double-foo", "double-bar", nullptr);
// tree1 doesn't have the new property

tree1 = ValueTree();
// tree1 is empty now

If you put something heavy as var property, it is stored as a ReferenceCountedObject, hence it will be automatically deleted, when no tree references it any longer.


1 Like