Archived Forum Post

Index of archived forum posts

Question:

C++ JSON Memory Management?

Jul 21 '16 at 18:12

When constructing JSON parameter for Dropbox endpoint /upload_session/append_v2:

    CkJsonObject jsonParams;
    jsonParams.AddObjectAt(-1, “cursor");
    CkJsonObject *jsonCursor = jsonParams.ObjectOf(“cursor");
    jsonCursor->AddStringAt(-1, "session_id", sessionIdStr);
jsonParams correctly ends up with a nested “cursor” object containing “session_id”. So it appears that jsonParams and jsonCursor shares some memory. So we aren’t sure if we should we explicitly delete jsonCursor, or just let jsonParams goes out of scope and destructs.


Accepted Answer

This simple answer is this:

In C++, a Chilkat object returned by a method call must always be deleted by the caller.

Here's more information for understanding:

All Chilkat objects in all programming languages (C++, Java, Objective-C, Perl, Python, ActiveX/COM, etc.) are simply references to an underlying implementation object (call it the internal "Cls" object). The Cls object is reference counted. When the latest external reference is removed, it is automatically deleted.

For example, if you have a CkSocket object, it references an internal ClsSocket implementation object. The CkSocket::CloneSocket method can be called to return a new instance of CkSocket that references the same underlying ClsSocket. Now there are two CkSocket objects referencing the same underlying ClsSocket. The underlying ClsSocket is automatically deleted when the last CkSocket referencing it is deleted.

The JSON, XML, ASN, and MIME Chilkat objects are similar in the following way: Each Cls object is in turn a reference to a single node within an underlying tree-like document (i.e. the document has a root node, which has N children, each of which can have N children, and so on.) As long as a single Cls object exists that references some node in the tree, the entire tree is kept in memory. The XML and JSON API's provide a method to get back to the root node from any node in the tree (JsonObject.GetDocRoot, and Xml.GetRoot).

Therefore, you can (and should) delete the jsonCurser. Assuming it's the only reference to it's underlying Cls object, the Cls object is deleted. If that Cls object was the last reference to the underlying JSON document, then the entire JSON document is deallocated. (In your case, it is not because the jsonParams object has a reference to it's Cls object, which in turn holds a reference to the same JSON document.)