为什么operator new需要构造函数是public?

Why does operator new need constructor to be public?

我试图找到 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 private.

#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

为什么不能像 Singleton 一样 operator new 调用 private constructor

It seems like constructor is called by operator new right?

没有。 new Foo()new expression,它尝试分配存储(通过 operator new),然后尝试构造对象(通过 Foo 的构造函数)。所以对象是从main()的上下文构造的,它不能访问Foo的构造函数而导致错误。例如,如果您将 main() 设为 Foofriend,它将编译正常。