Jump to content

Destructors and Memory Management

- - - - -

  • Please log in to reply
3 replies to this topic

#1
davidthefat

davidthefat

    Learning Programmer

  • Members
  • PipPipPip
  • 82 posts
Is it a bad idea not to use destructors? Will it lead to memory leaks and stuff in the long run? Also I am assuming it is more crucial to have better memory management in embedded systems right? What are some very good memory saving techniques?
All I use are constructors, now that I think about it, doesn't seem "correct" since destructors exist and I am not using them...

#2
JCoder

JCoder

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 245 posts
Change the language to some using automatic memory management and you are done. Destructors are a C++ only thing.
And in embedded systems it is better to use C, not C++, because C++ incurs some code size overhead.

#3
thechef

thechef

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
In the book "Effective C++" by Scott Meyer, he recommends creating destructors whenever you have dynamically allocated memory. Thus, if you ever use "new" in your constructor, you should call delete in your destructor.

Another nifty trick is to use smart pointers. Include memory.h. Then use a smart pointer instead of an ordinary pointer. For instance, to declare a pointer to "MyClass", do this
auto_ptr<MyClass> myPtr(new MyClass());

Smart pointers are cool because they can be treated as regular pointers but they delete themselves. Cool!
I don't document code. If it was hard to write, it should be hard to read ;)

#4
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
It depends on what's in your class. If you have resources that need to be gracefully released (pointers, open files, etc) then you should have a destructor. If you have resources that can simply be released, then a destructor isn't needed.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users