我试图找到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
不能像Singleton一样调用私有constructor
?
构造函数似乎是由
operator new
调用的,对吗?
否。new Foo()
是新的表达式,它尝试分配存储(通过operator new
(,然后尝试构造对象(通过CCD11的构造函数(。因此,该对象是从main()
的上下文中构造的,CCD_12无法访问Foo
的构造函数,从而导致错误。例如,如果您将main()
设置为Foo
的friend
,它将编译良好。