But is that still exception safe?
No. If the construction of the string
to pass as the other argument to Add
throws, then the dynamic object may be leaked. It is unspecified which argument is created first.
The original code ensures that the dynamic object is assigned to a smart pointer before anything else happens: the only thing that could fail is the creation of the smart pointer itself, in which case it will delete the object.
Or are there other more common ways to implement this?
It's generally a better idea to use the make_shared
function template, rather than using new
yourself. Not only does it guarantee exception safety by never exposing a naked pointer, it also makes more efficient use of memory by creating the controlled object and the shared reference count in a single block of memory.
obj->Add(boost::make_shared<JSONNode>(), "firstElement"); // or std:: in C++11