http://efesx.com/2009/12/01/public-operator-new-and-private-operator-delete/
在这篇文章中,我读到这段代码应该给出一个错误:
#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;
}
我用 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]
在这篇文章的评论中,我看到了这个链接 - Public operator new, private operator delete: getting C2248 "can not access private member" when using new
如果我理解它是正确的,它不会编译,因为编译器应该通过调用适当的操作符删除在构造函数抛出异常的情况下避免任何内存泄漏。但是为什么这段代码可以编译和工作?
#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;
}
标准是否正确?
那么这段代码呢?
#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;
}
它不能与 gcc 4.7.1 一起编译。
以及如何在标准库中实现这样的事情?
Comeau 并未编译所有这些示例:
"ComeauTest.c", line 15: error: function "Try::operator delete"
(declared at line 9) is inaccessible Try *t = new Try; ^
谁能给我详细解释一下,好吗?