std::unique_ptr<XmlElement> vs XmlElement

sorry it’s probable more C++ question than Juce, but could anyone help me to understand the idea to use std::unique_ptr<XmlElement> instead of straight XmlElement. What is the reason or advantage? Is it necessary?

I mean for example in AudioProcessor::setStateInformation() I see always people declare std::unique_ptr<XmlElement>
But wouldn’t be simpler if we just declare XmlElement?

Now I need to read xml from file in static method, so I am confused if I should get it like that:
XmlDocument xmlDoc(xmlFile);
or is it better to use that:
std::unique_ptr<XmlDocument> xmlDoc = std::make_unique<XmlDocument>(xmlFile);

Could anyone explain me the idea of using std::unique_ptr in such situations?

For any help thanks in advance.

Best Regards.

XmlElement represents a node in a tree structure, a tree of linked lists -its children are XmlElements too, so most of its “content” would be normally placed on the heap. There’s no problem with creating on the stack an XmlElement that will be used in a single scope, but if you need to pass it as a parameter or return, passing by value would imply deep copying or moving the whole structure. It makes more sense to create it on the heap, and pass a pointer.

Moving an XmlElement only swaps a few pointers at the root level, and does not traverse the XML tree.
But I agree that unique_ptr is a better choice for passing around, because then you don’t have to think about (or look into) these details.

1 Like

True, the move is cheap. It’s still safer, as in more general, to make them on the heap, especially if you don’t know what they’re going to be used for, as adds and inserts need pointers. If you know a node is always going to be root, moving may be fine.

1 Like

Great thanks for explanations.