为什么操作符new需要构造函数是公共的



我试图找到operator newconstructor之间的关系。

#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()设置为Foofriend,它将编译良好。

最新更新