Using std::shared_ptr to Ensure Returned Chilkat Objects are Deleted in C++
The Chilkat C++ library documentation specifies that objects returned by methods like ObjectOf are dynamically allocated and must be deleted by the application using the standard C++ delete operator.
Because std::shared_ptr uses delete as its default deleter, you can simply pass the raw pointer returned by the Chilkat method directly to the std::shared_ptr constructor.
How to Implement It
Here is the correct syntax to wrap the returned Chilkat object:
#include <CkJsonObject.h>
#include <memory> // Required for std::shared_ptr
void ProcessJson(CkJsonObject& json, const char* jsonPath) {
// 1. Call the Chilkat method and immediately wrap the result in a shared_ptr.
// If json.ObjectOf returns nullptr (failure), the shared_ptr will be empty.
std::shared_ptr<CkJsonObject> jsonObj(json.ObjectOf(jsonPath));
// 2. Check if the pointer is valid before using it.
if (jsonObj) {
// Access members using the arrow operator ->
const char* value = jsonObj->stringOf("someMember");
}
// 3. Automatic Cleanup:
// When 'jsonObj' goes out of scope (end of function), the std::shared_ptr destructor
// is called. It will automatically call 'delete' on the underlying CkJsonObject*,
// ensuring no memory is leaked.
}
Why this works
- Default Deleter:
std::shared_ptrautomatically defaults to usingdelete ptr;when it is destroyed. Since Chilkat requires standarddelete(not a customFree()orRelease()function), no custom deleter logic is required. - Null Safety: If
json.ObjectOffails and returnsNULL(nullptr), thestd::shared_ptrwill simply be initialized as empty (null). When it goes out of scope,std::shared_ptrsafely ignores the null pointer, so you don't need to add extra checks for deletion.
Alternative: std::unique_ptr
If you do not need to share ownership of this object across multiple parts of your application, std::unique_ptr is often the preferred choice. It is lighter weight and makes it clear that the current scope owns the returned object.
// unique_ptr is often better if you don't need to share the pointer
std::unique_ptr<CkJsonObject> jsonObj(json.ObjectOf(jsonPath));
if (jsonObj) {
// Use normally
}
// Automatically deleted here