Style Question with DynamicObject()

Awhile back I threw together something like this in a hurry:

DynamicObject *obj = new DynamicObject();

obj->addProperty (...);
obj->addProperty (...);
obj->addProperty (...);

return JSON::toString (obj);

Generally, whenever I (begrudgingly) call new, the results go immediately into a smart pointer (say ScopedPointer in JUCE). But that isn’t quite right here. DynamicObject is reference counted object. It get’s cast to var by JSON::toString(), and delete will get called by the ref. counting logic. So delete from a smart pointer would be deleting twice. Even in a hurry, I wasn’t a complete idiot, I actually put a comment by the new indicating how the life cycle was being managed. But, once this little throw together left my hands, the lines between new and return grew, and eventually picked up fail logic. Then “return String::empty” caused a leak of a now fairly bloated DynamicObject.

I can think of a number of different ways to get back to a more RAII approach, such as:

var obj (new DynamicObject());

obj.getDynamicObject()->addProperty(...);
...

return JSON::toString (obj);

But they all feel ‘off’ to me. One of the things I admire about Juce is the general legibility of the code. To me, a line like:

ScopedPointer<class> obj = new class();

Is self documenting, new will be matched when the container goes out of scope.

var obj (new DynamicObject());

Not so much. I get it, but it seems to require an explicit comment for the person to follow who, as we can see, may not read the comment…

Sorry, not really a specific question, but I would be interested in hearing different thoughts on how to best manage reference counted objects.

1 Like

Personally, I’d probably do this:

[code]DynamicObject::Ptr obj = new DynamicObject();

obj->addProperty (…);
obj->addProperty (…);
obj->addProperty (…);

return JSON::toString (obj);
[/code]

(just noticed there’s no typedef for DynamicObject::Ptr - I should add one of those)

1 Like

Yes, ReferenceCountedObjectPtr seems like the most obvious choice. In fact, it’s the solution I used for the cleanup. But I wondered if no typedef meant there was a better solution you had in mind.

I’m actually still trying to figure out if I really like the ::Ptr thing. It’s neat, but it seems like it could be confusing for code maintainers if it’s not consistent.

That is, I’m wondering if, in embracing it, I should be providing a typedef for a ScopedPointer, ReferenceCountedObjectPtr, etc. (whatever is appropriate) most the time. I’d be interested in your thoughts on the syntax.

I once heard Geddy Lee, from “Rush”, joke about Neil Peart being “the NEW guy!” - since he’d only been with the band since the mid 70s. That’s sort of my relationship with C++. Just another decade or two and I’ll get the hang of it…

Thanks!