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

时间:2021-07-05 02:46:40

标签: c++ constructor new-operator

我试图找出 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 调用私有的 constructor,就像 Singleton 一样?

1 个答案:

答案 0 :(得分:2)

<块引用>

看起来构造函数是由 operator new 调用的,对吗?

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