Thread: C++ Multiple Calls to Destructor

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Apr 2007
    Posts
    102

    C++ Multiple Calls to Destructor

    Hey all,

    I'm currently working on creating a resource management system for use in my own projects.

    My original idea was to prevent loading a resource multiple times into memory. For Example: Two objects both need to draw the same image;

    I tried to set this functionality up by overriding new and delete.
    When a resource is dynamically allocated, it checks to make sure that resource doesn't already exist. If it does, it returns the address of the already existing resource. Otherwise it returns allocated memory.

    Obviously I have run into a lot of little tricks with Constructors and initializer lists overwriting already loaded resources, but it works mostly to my liking.

    I overwrite the delete to only free the memory if the resource has no more objects referring to it. My current and only issue is that after calling delete and the 'images' destructor from an instance. Any other references to deleting that 'image' do not call the 'images' destructor.

    Code:
    Image* x = new Image("File1");
    Image* x2 = new Image("File1");
    
    // At this Point, x == x2 due to overridden new operator; they reference same file.
    
    delete x;  // Calls ~Image() , doesn't free memory for the image
    delete x2; // Does not Call ~Image(), does free memory for the image
    
    // Reversing the order, yields the same result. x2 will call the destructor, x will not.
    I know there are a lot of wrong practices going on here, but I'm ok with that. Can anyone tell me if a destructor physically marks an object as not being 'that type of object' or something similar?
    Last edited by JJFMJR; 09-20-2011 at 10:51 PM.
    My Favorite Programming Line:
    Code:
    #define true ((rand() % 2) ? true : false)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 08-29-2011, 01:35 PM
  2. for loop that calls multiple functions
    By elsparko in forum C++ Programming
    Replies: 2
    Last Post: 12-14-2009, 07:10 AM
  3. Replies: 4
    Last Post: 04-28-2008, 04:13 PM
  4. multiple packets received between recvfrom calls
    By ufsargas in forum Networking/Device Communication
    Replies: 4
    Last Post: 06-30-2006, 08:03 AM
  5. pure virtual calls in destructor
    By FillYourBrain in forum C++ Programming
    Replies: 2
    Last Post: 08-21-2003, 08:31 AM

Tags for this Thread