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/
在这篇文章中,我读到这段代码应该给出一个错误:
#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; ^
谁能给我详细解释一下吗?
最佳答案
- 看来您对第一个示例的看法是正确的。
第二个和第三个示例涉及 POD 类型。还有initialization differences发挥作用。
在第二个示例中,您的结构未初始化。没有出现任何问题。
相反,在第三个示例中,结构确实初始化,因此您得到第一种情况。
编辑:
然后,operator new
本身可以抛出异常。标准(c++11 darft 说):
If the
new
expression terminates by throwing an exception, it may release storage by calling a deallocation function (3.7.4.2). If the allocated type is a non-array type, the allocation function’s name isoperator new
and the deallocation function’s name isoperator delete
.
有点不清楚,作者想要表达什么,说它可能释放存储。如果它被发布,它似乎是实现定义的。
无论如何,您可以尝试使用不抛出的新
版本:
void *operator new (size_t size, std::nothrow_t) throw() {
return malloc(size);
}
关于c++ - 私有(private)运营商删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12536280/