Thread: Of Destructors And Destruction...

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    265

    Of Destructors And Destruction...

    This is another of my what-if questions. How do member functions behave in objects being destroyed? Example: I have an object. lets call him Bob. Excuse the poor syntax as im writing this on the fly, and not compiling it.
    Code:
    class Bob
    {
    	public:
    		Bob();
    		~Bob();
    		static void hokey_pokey() { while(1) { this->shake(); } return; }
    	private:
    		void shake(); // do whatever.
    };
    What happens to executing member functions when they are destroyed? For example, if I were running hokey_pokey in a thread, and for some reason delete were called on a Bob floating around on the heap. What would happen to the function shake when it was executed? Would it continue trying to execute the function, and crash because instead of instructions it gets garbage? What about static member functions, would they survive? Any ideas would be greatly appreciated. Thanks for your time.

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    161
    I know you said to excuse the syntax, but there is a glaring error in the fact that you use the this pointer in your static member function. I'm sure you know that static functions execute outside the context of the object, so this is not available.

    As for your question, it depends on the function. When an object is destroyed, the member data is destroyed -- not the code. To understand this, you have to know how classes actually work.

    Generally, a class like this:
    Code:
    class MyClass 
    {
      public:
        void add(int i) { num += i; }
    
      private:
        int num;
    };
    Will compile down to something equivalent to this:
    Code:
    struct MyClass
    {
      int num;
    }
    
    void add(MyClass* this, int i)
    {
      this->num += i;
    }
    So the functions are still around even when the class itself is gone.

    To break it down to the simplest answer: if your member function does not access member data or call other member functions, it will probably continue to run without any problems.

    However, I'm fairly sure this type of behavior is undefined and should be avoided in all situations.

    Hope that helped.

    -tf

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. deques, vectors and destructors.
    By Hunter2 in forum C++ Programming
    Replies: 4
    Last Post: 02-22-2005, 06:29 PM