I was trying to find the relationship between operator new
and 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;
}
Here's the output.
new()
constructor()
It seems like constructor
is called by operator new
right? Then I set 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;
}
And I got a compilation error
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
Why can't operator new
call private constructor
, just like Singleton?
It seems like constructor is called by
operator new
right?
No. new Foo()
is new expression, which attempts to allocate storage (via operator new
) and then attempts to construct the object (via the constructor of Foo
). So the object is constructed from the context of main()
, which can't access the constructor of Foo
and causes the error. For instance if you make main()
the friend
of Foo
it'll compile fine.