0
warning on overloading new operator for class
refer code below. Why it shows warning on line from main function where delete ptr is there: 'void operator delete(void*, std::size_t)' called on pointer returned from a mismatched allocation function [-Wmismatched-new-delete]' #include <iostream> using namespace std; class Test { public: void* operator new(size_t size) { cout << "new requested for " << size << " bytes\n"; void* ptr = ::operator new(size); return ptr; } Test(int a,int b) : m_a(a),m_b(b){cout<<"Ctor\n";} ~Test() {cout<<"Dtor\n";} void display() {cout << m_a << " " << m_b << endl;} private: int m_a; int m_b; }; int main() { Test* ptr = new Test(1,2); ptr->display(); delete ptr; return 0; }
10 odpowiedzi
+ 4
As far as I understand, the warning is because when defining operator new, it also expects you to explicitly define operator delete in the Test class.
I don't know enough C++ to explain why or under what circumstances this is necessary.
+ 3
trying out Lisa's reply seems to silence the warning.
https://sololearn.com/compiler-playground/clEgBeY970Uf/?ref=app
+ 3
Ketan Lalcheta
You're right. C++ is fundamentally flawed. the compiler does no further checks on the delete overload. it just checks if it's defined.
I used free when I should logically used Lisa's ::operator delete, yet the compiler accepted it without complaints.
I investigated further and it seems it doesn't matter what you put or don't put inside the delete overload.
as long as delete is defined, no warnings are raised ...
https://sololearn.com/compiler-playground/cbAiNAqvATfx/?ref=app
0
Where?
0
Its because you are deleting the ptr twice
0
Delete the return 0; because you already deleted the memory
0
Also thanks Bob_Li for writing noexcept with overloaded delete operator. Good to notice this as we are sure that freeing memory will not throw exception
0
I don't know if this helps anything, but I just submitted your code to GPT-4o and it suggests
void operator delete(void* ptr) {
cout << "delete\n";
::operator delete(ptr);
}
this seems to parallel your operatir new?
0
Yes this is perfect fit for operator new.
But two cases to wonder now:
1. Why it gives warning when only new is overloaded
2. Why it did not fail or atleast warn when new and free is mixed. This is more serious stuff for compiler rather than throwing warming for missing delete