954,170 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Is there a way to prevent creating objects on heap?

Yesterday I saw a question that was asking to prevent creating objects on heap.

After some thoughts, I came out the following:

class Foo
{
public:
    Foo(const Foo& f) {}
    static Foo getAnInstance()
    {
        return Foo();
    }
private:
    Foo() {}
};


But this can only guarantee the first object is on stack and it can’t go further because there is a public copy ctor.

I haven't seen the point of the question, but it's fun to think about; so my question: Is there a way to do so?

jaux
Newbie Poster
15 posts since Oct 2007
Reputation Points: 10
Solved Threads: 2
 

methods of a class are never ever on the stack -- only data objects go there.

int main()
{
    Foo f; // object f goes on the stack, but not the methods of that object.
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,043 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,341
 

Thank you, Dragon. Does that mean that, on our side (not the client side), to restrict the location of object creation is pointless? I mean that it's client's responsibility to determine where his/her objects should be located.

jaux
Newbie Poster
15 posts since Oct 2007
Reputation Points: 10
Solved Threads: 2
 

see: More Effective C++: 35 More Ways to Improve Your Programs and Designs (Scott Meyers)
ITEM 27. Requiring or Prohibiting Heap-Based Objects.
and http://www.aristeia.com/BookErrata/M27Comments_frames.html

vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 

Thank you, vijayan121. I am going to take a look at the item.

jaux
Newbie Poster
15 posts since Oct 2007
Reputation Points: 10
Solved Threads: 2
 

I've gotten the point and solution :)
Thank you guys!

jaux
Newbie Poster
15 posts since Oct 2007
Reputation Points: 10
Solved Threads: 2
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You