Creating 'new' elements without using new


I am working on a project that was following the tutorial, in the tutorial they use the keyword ‘new’ to create new elements and add them, like this

 XmlElement* newItem = new XmlElement("ITEM");

I’m looking to do this the correct way so I’m changing my statement to be like this:

auto newItem = std::make_unique<XmlElement>("ITEM");

The issue I think I am encountering is that all of the XmlElement functions will only accept regular pointers and not unique_pointers, so how would I go about generating this new element as a unique pointer to that object on the heap, but then pass it to the functions like a normal pointer?

the error I am getting is this:

Error (active) E0413 no suitable conversion function from "std::unique_ptr<juce::XmlElement, std::default_delete<juce::XmlElement>>" to "juce::XmlElement *" exists

I think I understand what needs to be done, is instead of using a normal pointer and adding it with ‘new’ i need to use the unique_pointer that has its lifetime defined by the object it is owned by, but I just need a bit of help with the syntax in order to convert that to the type of pointer that is used in all of the functions everywhere else, thanks in advance for the help.

Check the docs:

addChildElement takes ownership of the pointer, so you don’t need to use std::make_unique.

However, if you want to wrap it into a unique pointer and pass the ownership to a function that takes a raw pointer later on you want to call newItem.release()

1 Like

This is the correct answer. At the moment, this is the best you can do:

auto element = std::make_unique<XmlElement>("ITEM");

However, in the future, I believe that the APIs of these classes will be updated so that they properly support smart pointers, in which case you would write this:

auto element = std::make_unique<XmlElement>("ITEM");
1 Like