我试图找出 operator new
和 constructor
之间的关系。
#include <iostream>
using namespace std;
class Foo {
public:
void* operator new(size_t t) {
cout << "new()" << endl;
}
void operator delete(void* ptr) {
}
Foo() {
cout << "constructor()" << endl;
}
};
int main() {
Foo* f = new Foo();
delete f;
return 0;
}
这是输出。
new()
constructor()
好像 constructor
是由 operator new
调用的吧?然后我将 constructor
设为私有。
#include <iostream>
using namespace std;
class Foo {
public:
void* operator new(size_t t) {
cout << "new()" << endl;
}
void operator delete(void* ptr) {
}
private:
Foo() {
cout << "constructor()" << endl;
}
};
int main() {
Foo* f = new Foo();
delete f;
return 0;
}
我遇到了编译错误
root# g++ main.cpp
main.cpp: In function ‘int main()’:
main.cpp:13: error: ‘Foo::Foo()’ is private
main.cpp:19: error: within this context
为什么不能 operator new
调用私有的 constructor
,就像 Singleton 一样?
答案 0 :(得分:2)
看起来构造函数是由 operator new
调用的,对吗?
没有。 new Foo()
是 new expression,它尝试分配存储空间(通过 operator new
),然后尝试构造对象(通过 Foo
的构造函数)。所以对象是从main()
的上下文构造的,它不能访问Foo
的构造函数而导致错误。例如,如果您将 main()
设为 friend
的 Foo
,它会编译正常。