Creating 'new' elements without using new

#1

Hello,

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");
 tutorialData->addChildElement(newItem);

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");
 tutorialData->addChildElement(newItem);

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.

0 Likes

#2

Check the docs:

https://docs.juce.com/master/classXmlElement.html#a9b9735dd8a98c5af71db4c532cd10a1c

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

0 Likes

#3

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

#4

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

auto element = std::make_unique<XmlElement>("ITEM");
tutorialData->addChildElement(element.release());

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");
tutorialData->addChildElement(std::move(element));
0 Likes