Thread: Object destroy itself?

  1. #1
    C = C - 1
    Join Date
    Mar 2008
    Posts
    15

    Post Object destroy itself?

    I made a linked list of dynamic objects, and a function to call them starting from the first one.
    I need to destroy a dynamic object using "this" pointer, or some other way...
    the problem is that if I call the destructor from inside of the class (some member function), it works, but causes a memory leak, if i call "delete this;" the program crashes.
    I'm a still a n00b in c++...

    thanks

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    It is ALMOST never right to call "delete this;".

    To find the correct way to do things, you probably would have to post (some of) your code.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    The nodes you allocate using new should be deleted via delete. That simple.
    Delete this is dangerous and should only be considered in special situations.
    But even better is using smart pointers. That will make sure they get deleted without a memory leak when the time is right.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Quote Originally Posted by matsp View Post
    It is ALMOST never right to call "delete this;".

    To find the correct way to do things, you probably would have to post (some of) your code.

    --
    Mats
    My previous company did that all over the place. Each of their objects contained a Delete() function which just did delete this;
    I never saw any problems when using it.
    What other situations of delete this; are actually wrong and why?
    The only bad use I can think of right now would be trying to delete an object that wasn't dynamically allocated.

  5. #5
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Yep, deleting objects on stack and the problem that it can leave a dangling pointer, if you aren't careful.
    I don't think it's that bad, but you should definitely be careful with it. There are some situations where it's helpful.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    C = C - 1
    Join Date
    Mar 2008
    Posts
    15

    Thumbs up thanks everyone!

    everything exept the deleting works. when I try to call the destructor, it just simply removes the linking to other obj. but does not deallocate the memory.
    "delete this;" wont work, and I don't know why...
    here's the code of my program:

    main.cpp
    Code:
    #include <iostream>
    
    class dyn_obj
    {
    public:
    	dyn_obj();
    	~dyn_obj();
    	void function(int &);
    	
    	dyn_obj *prev, *next;
    
    private:
    	bool del_now;
    };
    
    dyn_obj *first_obj = 0, //first object's mem address
    		*Prev_obj = 0; //the current object's address
    
    dyn_obj::dyn_obj():del_now(false)
    {
    	
    	next = 0;//set the link to the next object to 0, there is no next object yet
    	if( first_obj == 0 )//if this is the first object in the list
    	{
    		first_obj = this;//set this as the first object
    		prev = 0;//set prev to 0, this are no previous objects.
    	}
    	else//if NOT the first object
    	{
    		prev = Prev_obj; //link this object to the previous object
    		prev -> next = this;//link the previous object to this object
    	}
    	Prev_obj = this;
    }
    
    dyn_obj::~dyn_obj()
    {
    	if(next == 0)
    	{
    		if(prev == 0)//if this is the only object existing
    		{
    			first_obj = 0; //set first object to 0, no first object
    		}
    		else//if this is the last object in the list
    		{
    			prev -> next = 0; //remove the linking from the object before
    		}
    	}
    	else
    	{
    		if(prev == 0)//if this is the first object in the list
    		{
    			first_obj = next; //set the next object as the first one
    			next -> prev = 0;
    		}
    		else//if this object is somewhere in the middle of the list
    		{
    			prev -> next = next;//link the previous object to the next one
    			next -> prev = prev;//and vice versa
    		}
    	}
    }
    
    void dyn_obj::function(int & value)
    {
    	value++;
    	
    	if(del_now)delete this;
    	else del_now = true;
    }
    
    int call()
    {
    	int n = 0;
    	if( first_obj != 0 )//if the list is not empty
    	{
    		dyn_obj *object = first_obj;//create a pointer to the first object in the linked list
    		while( true )
    		{
    			object -> function(n);//call the object
    			if(object -> next != 0) object = object -> next;//if not last object, move to the next one
    			else break;
    		}
    	}
    	return n;
    }
    
    
    int main()
    {
    	for(int n = 0; n < 10; n++) new dyn_obj;
    	std::cout << "10 objects created. let's call them." << std::endl;
    	std::cout << "the function \"function\" was called " << call() << " times." << std::endl;
    	std::cout << "let's call the functions a second time, making the objects delete themselves." << std::endl;
    	call();
    	std::cout << "deleted.";
    	std::cin.get();
    }
    Last edited by cminusminus; 03-26-2008 at 09:27 AM.

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    This implementation will confuse and creates bugs. That's all.
    Reconsider it to a more true OOP implementation.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I would personally like to see a "holder" (aka container) object for your dyn_obj's - this would have the pointers "first_obj" and "prev_obj" [which traditionally are called head and tail respectively, but that's your choice - your names are certainly better than "a" and "b"!].

    Then let the holder deal with deleting the objects.

    Your current construction makes the whole thing a bit convoluted.

    I don't see any reason why the current design doesn't de-allocate the memory, however.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Not to mention - that removing node from the middle of the 2-linked list requires to update 4 pointers and not 2
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  11. #11
    C = C - 1
    Join Date
    Mar 2008
    Posts
    15
    yes, i'd like to make an another class where to place that call() function, the *first_obj and *prev_obj pointers and make it "parent" to the dyn_obj class, but when I tried I got like 40 errors, and posted that one, I still need to learn the class inheritance and some other important stuff.

  12. #12
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    There should be no need for inheritance for such a class - one class CONTAINS the other class, but they are not related, just like the class below is not inheriting "string":
    Code:
    class person
    {
       string name;
    ...
      public:
       const string &getName() { return name; }
    ...
    }
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  13. #13
    C = C - 1
    Join Date
    Mar 2008
    Posts
    15
    Quote Originally Posted by vart View Post
    Not to mention - that removing node from the middle of the 2-linked list requires to update 4 pointers and not 2
    4? two of them will be destroyed...
    ok it's always good practise

  14. #14
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    Quote Originally Posted by laserlight View Post
    For further reading: Is it legal (and moral) for a member function to say delete this?[/url]
    Oh you silly programmers with your hyperboles.

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I would like to see something along the lines of this:
    Code:
    template<typename Type> class CLinkedList
    {
    public:
    	//CLinkedList(): pNext(NULL), pPrevious(NULL), pObject(NULL), pBeginOrEnd(NULL) { }
    	CLinkedList(CLinkedListBeginOrEnd<Type>* pBeginOrEnd): pNext(NULL), pPrevious(NULL), pObject(NULL), pBeginOrEnd(pBeginOrEnd) { }
    	//CLinkedList(const CLinkedList<Type, Allocator>& rCopy);
    	void InsertAfter(CLinkedList<Type>* pAfter);
    	void InsertBefore(CLinkedList<Type>* pBefore);
    	void InsertAtBeginning();
    	void InsertAtEnd();
    	void Remove();
    	//void Initialize(CLinkedListBeginOrEnd<Type, Allocator>* pBeginOrEnd);
    	//CLinkedList& operator = (const CLinkedList<Type, Allocator>& rCopy);
    	Type* pObject;
    
    private:
    	CLinkedList* pNext;
    	CLinkedList* pPrevious;
    	CLinkedListBeginOrEnd<Type>* pBeginOrEnd;
    };
    CLinkedListBeginOrEnd is optional, but is useful is you want your lists to have a head and tail pointer.
    Implementation is missing on purpose.
    Perhaps you might get an idea of what is possible via linked lists in C++...
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. using this as synchronization object
    By George2 in forum C# Programming
    Replies: 0
    Last Post: 03-22-2008, 07:49 AM
  2. Why Does The destructor destroy the original object??
    By chottachatri in forum C++ Programming
    Replies: 32
    Last Post: 03-12-2008, 08:46 AM
  3. circular doubly linked list help
    By gunnerz in forum C++ Programming
    Replies: 5
    Last Post: 04-28-2007, 08:38 PM
  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