Skip to content

This is a C project not a C++ project #40

@Elmue

Description

@Elmue

Hello

You wrote a nice library.
But it breaks C++ rules.

It is wrong to require the user of your library to call 'delete' to detroy a JSONValue. Anybody who forgets this will have a MEMORY LEAK.

In a correclty programmed C++ library there must never be the need to ever use 'delete' for a class. C++ classes have a destructor which should do all the work of freeing memory.

The correct way would be to use a member function Parse() instead of a static function Parse().

JSONValue myValue;
bool success = myValue.Parse(stringData);

Then the destructor of myValue does the clean up of the memory alone without ever calling "delete".

It is very easy to do this:
First you put the destructor code into a separate function which also sets type = JSONType_Null

    JSONValue::~JSONValue()
    {
        Clear();
    }
    JSONValue::Clear()
    {
	if (type == JSONType_Array)
	{
		JSONArray::iterator iter;
		for (iter = array_value->begin(); iter != array_value->end(); iter++)
			delete *iter;
		delete array_value;
	}
	else if (type == JSONType_Object)
	{
		JSONObject::iterator iter;
		for (iter = object_value->begin(); iter != object_value->end(); iter++)
		{
			delete (*iter).second;
		}
		delete object_value;
	}
	else if (type == JSONType_String)
	{
		delete string_value;
	}

        type = JSONType_Null;
}

Then you write a member function Parse like this:


bool JSONValue::Parse(const wchar_t **data)
{
        Clear();

	// Is it a string?
	if (**data == '"')
	{
                wstring str;
		if (!JSON::ExtractString(&(++(*data)), str))
			return false;

                 string_value = new wstring(str);
                 type = JSONType_String
                 return true;
        }

        etc....

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions