How To Prevent Creating Objects On Heap
Yesterday I saw a C++ interview question that was asking the interviewees to prevent the clients from creating objects on heap. That is, you write a class and your class users can’t use new to create an object.
Here is my solution:
class Foo
{
public:
Foo(const Foo& f) {}
static Foo getAnInstance()
{
return Foo();
}
private:
Foo() {}
};
Explanation:
To prevent users from creating objects on heap, I basically can’t give them any public constructors (ctor); therefore, I need to write at least one ctor myself and make it private since if I fail to do so, the compiler will generate a public default ctor for me and that is exactly what I don’t want. Then the user can only use the static member function getAnInstance to get an object to use.
Analysis:
In fact, my solution contradicts the explanation because I actually have a public ctor — the copy ctor. The copy ctor makes the following usage work:
Foo f0 = Foo::getAnInstance();
But because there is a copy ctor, after the user get his/her first object, he/she can do the following:
Foo* f1 = new Foo(f0);
This is saying that my solution can only guarantee the first object is on stack and it can’t go further.
So, my solution fails to solve the question.
p.s. I haven’t really seen the point of the interview question, but it’s interesting to think about ;)
Update:
The correct solution is to overload the new operator and make it private. Credit to DANIWEB