Hey, this is the first christmas for jaux.net, and today is my first boxing day to crash a door. Got nothing but happy holidays :)
Merry Christmas, everyone!
Hey, this is the first christmas for jaux.net, and today is my first boxing day to crash a door. Got nothing but happy holidays :)
Merry Christmas, everyone!
Yesterday, we several friends had a wonderful hot-pot party night. We then called ourselves “Hot-pot Party” — such a amazing party name.
We couldn’t get together like last night every night and talk, but it’s not a big problem. We can’t talk face to face, let’s talk virtually.
Here we go, Hot-pot Party!
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() {}
};
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.
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 ;)
The correct solution is to overload the new operator and make it private. Credit to DANIWEB