[SOLVED] Add field to XmlElement without memory leak

I’m trying to add a separate field to the XML-binary data in getStateInformation(), which is not part of the AudioValueTree:

void OdinAudioProcessor::getStateInformation(MemoryBlock &destData) {
	auto state = m_value_tree.copyState();
	std::unique_ptr<XmlElement> xml(state.createXml());

	// add separate field  
	std::unique_ptr<XmlElement> test_element 
			= std::make_unique<XmlElement>(XmlElement("TestElement"));
	test_element->setAttribute("data", "Hello JUCE!");
	xml->addChildElement(test_element.get());

	copyXmlToBinary(*xml, destData);
}

As I use a unique_ptr, the data is destroyed after this function call, which causes a segfault. When using a plain pointer, allocating memory with new, everything works out (provided I don’t use delete). But in this case I would have a memory leak, since I never deallocate the memory…

Anybody knows how to resolve this situation? Why does copyXmlToBinary() keep pointers in the first place instead of resolving to the actual data?

There will be no memory leak with a raw pointer/new, the XmlElement transfers ownership of the passed in child element to itself. If there was a memory leak, the Juce memory leak detection would have caught that.

1 Like

Awesome!

Thanks for the quick reply!