Possible Duplicate:
Public operator new, private operator delete: getting C2248 “can not access private member” when using new
http://efesx.com/2009/12/01/public-operator-new-and-private-operator-delete/
In this article i read that this code should give an error:
#include <cstdlib>
struct Try {
Try () { /* o/ */ }
void *operator new (size_t size) {
return malloc(size);
}
private:
void operator delete (void *obj) {
free(obj);
}
};
int main () {
Try *t = new Try();
return 0;
}
I tried it with gcc 4.7.1:
Compilation finished with errors: source.cpp: In function 'int
main()': source.cpp:11:14: error: 'static void Try::operator
delete(void*)' is private source.cpp:17:22: error: within this context
source.cpp:11:14: error: 'static void Try::operator delete(void*)' is
private source.cpp:17:22: error: within this context source.cpp:17:10:
warning: unused variable 't' [-Wunused-variable]
In comment in this article i saw this link - Public operator new, private operator delete: getting C2248 "can not access private member" when using new
If i unserstand it correct, it doesn't compile because compiler should avoid any memory leaks in situations when there are exception thrown from constructor by calling the appropriate operator delete. But why this code compile and works?
#include <cstdlib>
struct Try {
void *operator new (size_t size) {
return malloc(size);
}
private:
void operator delete (void *obj) {
free(obj);
}
};
int main () {
Try *t = new Try;
return 0;
}
Is it correct by standard or not?
And what about this code?
#include <cstdlib>
struct Try {
void *operator new (size_t size) {
return malloc(size);
}
private:
void operator delete (void *obj) {
free(obj);
}
};
int main () {
Try *t = new Try();
return 0;
}
It doesn't compile with gcc 4.7.1.
And how things like this should be implemented in the standard library?
Comeau doesn't compile all these examples:
"ComeauTest.c", line 15: error: function "Try::operator delete"
(declared at line 9) is inaccessible Try *t = new Try; ^
Can anyone explain me this in detail, please?