Thread: Object instantiation

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    29

    Object instantiation

    HI there,

    Essentially a C programmer, I would like to know when an object should be instsantiated on the stack and when on the free store.

    eg for class fred, we can create objects as follows:

    fred myobject;

    // use myobject
    // myobject.function();

    OR

    fred myobject = new fred();

    // use myobject
    // myobject->function();

    Can anyone giove some examples...


    Thanks,


    bigSteve
    bigSteve

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    >> fred myobject = new fred();

    Should be:

    fred * myobject = new fred();

    Generally, you should intantiate from the stack whenever possible. Cleanup of the variable occurs automaticly once the function it was created exits, making it a 'safer' mechanism. The only time you should use dynamic allocation is when:

    1) The data needs to be used somewhere outside of the function it was created in.

    2) The data is needed from within the function it is created but the amount of data needed might overrun the stack. In other words, if you need a million 'freds', you should dynamically allocate them.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    Registered User
    Join Date
    May 2002
    Posts
    66
    I would disagree with that, you want to use the stack when you may have few small objects, but you really don't want to polute the stack with lots of objects.

    There is a wonderful thing called auto_ptr, while in it's incarnation it doesn't support arrays it can allocate and deallocate objects quite nicely.

    For example:
    Code:
    #include <memory>
    using namespace std;
    
    class MyObject
    {
    //  lots of stuff here
    };
    ...
    int main() {
      ...
    
      auto_ptr<MyObject> ptr(new MyObject());
    
      ptr->access();  // or whatever you do with you object
    
      return 0;   // this will clear up the object and delete it
    }
    Avoid the stack, from many years of experience, the stack allocated objects have caused me a lot of grief (mostly when you are not sure how big the object may be).

    If your object looks something like this:

    Code:
    class BlobEditor
    {
    private:
      char buffer[1000000];
    
    ...
    ...
    }:
    
    int main() {
      MyArray BlobEditor[100];
    
      return 0;
    }
    On many platforms that code will cause your program to crash (on windows the executable can be terminated by the OS and you will never know why).

    Use the stack for small objects (under 1k), the heap gets big objects.

  4. #4
    Registered User
    Join Date
    May 2003
    Posts
    1,619
    auto_ptr is nice but not at all container-safe.

    Look into boost::shared_ptr.

    Boost is incredibly easy to install (with the exception of a very few features, you just copy all the headers into a subdirectory of your compiler's include directory), and it's very powerful. I use it all the time, it's become part of my normal programming. Also, being as it was written by many of the same people who wrote the STL, it's well created and many of the features will most likely become standard C++ in the future.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  5. #5
    Registered User
    Join Date
    Feb 2002
    Posts
    29
    Hi all,

    Thanks for all your comments. This does not seem to be a clear cut issue ....

    bigSreve
    bigSteve

  6. #6
    Registered User
    Join Date
    May 2003
    Posts
    161
    I just wanted to add a couple points.

    1. The main reason to use a smart pointer like auto_ptr or the boost shared pointers is to make your code exception safe. Consider this code:
    Code:
    void do_something()
    {
      throw string("error");
    }
    
    void func()
    {
      MyClass* p = new MyClass;
      auto_ptr<MyClass> ap(new MyClass);
    
      do_something(); // exception is thrown
    
      delete p; // this never gets called
    }
    If for some reason, an exception is thrown and the stack is unwound past your function, the memory allocated to the bare pointer will be lost in the heap. With the auto_ptr, however, the destructor will be called and that will delete your object.


    2. I disagree with achacha's advice to avoid the stack. The size of an object is not an issue if you're making proper use of the STL and resource handles. The "BlobEditor" example could easily be rewritten to allow a local stack-allocated container:
    Code:
    class BlobEditor
    {
    private:
      std::string buffer;
      //...
    }:
    
    int main() {
      std::vector<BlobEditor> myVector;
      return 0;
    }
    Here, we have our container allocated on the stack as an auto variable. The content is actually on the heap, but we don't have to worry about cleaning it up. It is exception safe, clean, and concise.

  7. #7
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Interesting... I meant to post a new thread, but this seems to be related, so guess I'll post here.

    In my program, I have 4 array of HBITMAP's:
    HBITMAP gunImages[2][180];
    HBITMAP gunMasks[2][180];
    HBITMAP swordImages[360];
    HBITMAP swordMasks[360];

    Should this be replaced with 2-D vectors? Also, it works fine on WindowsXP, but I'm having an unknown bug on windows98 which will crash on an invalid page fault, although I'm not sure what's causing it. Is this potentially a problem?
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  8. #8
    Registered User
    Join Date
    May 2003
    Posts
    161
    > Should this be replaced with 2-D vectors?

    From the code you provided, it looks as if you're loading graphics (possibly for a game) that will probably only be loaded once and retained for the lifetime of the program. In that case, those are either global variables or they are members of an object that was probably dynamically allocated. In both of those cases, I'd leave them as arrays.

    If you plan on adding or removing items from those arrays as the program runs, or if they're member variables of objects allocated on the stack, I'd change them to vectors.

    Finally, if those are local variables, then I'd rethink the entire design instead of trying to stash them in vectors.


    > but I'm having an unknown bug on windows98 which will crash on an invalid page fault

    You might be accessing beyond the bounds of the array. Is it possible for you to load it into a debugger in a 98 system and find the faulty code?

  9. #9
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Yes, it's code that rotates two images 360 degrees on program start, then generates masks for them to save processing time. They're static members of a class called RotdPics

    >>load it into a debugger in a 98 system
    Ah yes, that would probably be an excellent idea Currently, I'm operating by making a change and sending it to a friend, but I'm hoping to get MSVC reinstalled on my old computer.

    The odd thing about the bug is that it is very inconsistent. It will crash at seemingly random points during the loading of the images/masks, and once it even didn't crash. There seem to be a couple of "favourite" crashing points, but the array index shouldn't be overstepped at any point as far as I can see. I guess I'll just have to wait until I get an opportunity to plug the code into Windows98
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. circular doubly linked list help
    By gunnerz in forum C++ Programming
    Replies: 5
    Last Post: 04-28-2007, 08:38 PM
  3. Binary Search Tree - object instantiation problem
    By patricio2626 in forum C++ Programming
    Replies: 3
    Last Post: 11-14-2006, 02:11 AM
  4. Question on l-values.
    By Hulag in forum C++ Programming
    Replies: 6
    Last Post: 10-13-2005, 04:33 PM
  5. A question about constructors...
    By Wolve in forum C++ Programming
    Replies: 9
    Last Post: 05-04-2005, 04:24 PM