E2157 Deleting an object requires exactly one conversion to pointer operator (C++)

From RAD Studio
Jump to: navigation, search

Go Up to Compiler Errors And Warnings (C++) Index

If a person uses the 'delete' operator on an object (Note: not a pointer to an object, but an object itself), the standard requires that the object defines exactly one "conversion to pointer operator", which will yield the pointer that gets freed.

Example 1:

class T2DTranslation {
	// ...
};

int _tmain(int argc, _TCHAR* argv[]) {
	T2DTranslation t;
	delete t; // E2157

	return 0;
}

Example 2:

#include <stdio.h>

class T2DTranslation {
private:
	int *coord;

public:
	T2DTranslation() {
		coord = new int[3];
	}

	operator int *() {
		puts("Conversion...");
		return coord;
	}
};

int _tmain(int argc, _TCHAR* argv[]) {
	T2DTranslation t;

	delete t;

	return 0;
}

In example 2, since 't' is not a pointer, but an object, the compiler will delete 'coord', because that is what the pointer conversion operator for the object yields. Having more than one conversion to pointer operator is illegal, because the compiler would not know which one to call.

This message can also appear if delete[] has been called but is not necessary (for example, you would call delete when working with pointers to dynamic memory, but not when working with pointers to a vector of type int).