Main Content

AUTOSAR C++14 Rule A18-5-11

"operator new" and "operator delete" shall be defined together

Since R2020b

Description

Rule Definition

"operator new" and "operator delete" shall be defined together.

Rationale

You typically overload operator new to perform some bookkeeping in addition to allocating memory on the free store. Unless you overload the corresponding operator delete, it is likely that you omitted some corresponding bookkeeping when deallocating the memory.

The defect can also indicate a coding error. For instance, you overloaded the placement form of operator new[]:

void *operator new[](std::size_t count, void *ptr);
but the non-placement form of operator delete[]:
void operator delete[](void *ptr);
instead of the placement form:
void operator delete[](void *ptr, void *p );

When overloading operator new, make sure that you overload the corresponding operator delete in the same scope, and vice versa. To find the operator delete corresponding to an operator new, see the reference pages for operator new and operator delete.

Polyspace Implementation

The rule checker raises a violation when you overload operator new but do not overload the corresponding operator delete, or vice versa.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <new>
#include <cstdlib>

int global_store;

void update_bookkeeping(void *allocated_ptr, bool alloc) {
   if(alloc) 
      global_store++;
   else
      global_store--;
}


void *operator new(std::size_t size, const std::nothrow_t& tag);
void *operator new(std::size_t size, const std::nothrow_t& tag) //Noncompliant
{
    void *ptr = (void*)malloc(size);
    if (ptr != nullptr)
        update_bookkeeping(ptr, true);
    return ptr;
}

void operator delete[](void *ptr, const std::nothrow_t& tag);
void operator delete[](void* ptr, const std::nothrow_t& tag) //Noncompliant
{
    update_bookkeeping(ptr, false);
    free(ptr); 
}

In this example, the overloads of operators operator new and operator delete[] are noncompliant because there are no overloads of the corresponding operator delete and operator new[] operators.

The overload of operator new calls a function update_bookkeeping to change the value of a global variable global_store. If the default operator delete is called, this global variable is unaffected, which might defy developer's expectations.

Check Information

Group: Language support library
Category: Required, Automated

Version History

Introduced in R2020b

expand all