DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Is there a way to prevent creating objects on heap? (http://www.daniweb.com/forums/thread100867.html)

jaux Dec 12th, 2007 5:27 pm
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?

Ancient Dragon Dec 12th, 2007 8:39 pm
Re: Is there a way to prevent creating objects on heap?
 
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.
}

jaux Dec 12th, 2007 9:04 pm
Re: Is there a way to prevent creating objects on heap?
 
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.

vijayan121 Dec 12th, 2007 9:04 pm
Re: Is there a way to prevent creating objects on heap?
 
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/M...ts_frames.html

jaux Dec 12th, 2007 9:22 pm
Re: Is there a way to prevent creating objects on heap?
 
Thank you, vijayan121. I am going to take a look at the item.

jaux Dec 12th, 2007 9:33 pm
Re: Is there a way to prevent creating objects on heap?
 
I've gotten the point and solution :)
Thank you guys!


All times are GMT -4. The time now is 5:31 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC