Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

11
  • Thanks for the answer. I really should have spotted the pointer problem, sorry. However, your answer did also teach me other things, and leave me with a few questions - mostly about this 'dynamic' versus 'automatic' allocation. To be frank, I have no idea what you're talking about - google for 'C++ automatic allocation' gives a first result that claims dynamic and automatic allocation are the same thing (cplusplus.com/forum/articles/416). So, sorry, but what are you actually talking about in regards to that? Commented Aug 19, 2010 at 22:33
  • @Stephen, what GMan is referring to that instead of saying TestClass* tc = new TestClass(1); you can also write TestClass tc(1); and it will construct an object with the same value. This is the preferred way in C++ over new/delete. You also missed out on the delete for tc and tc1, so these objects will never be destroyed. C++ doesn't have a garbage collector like C# or Java does, you have to take out the garbage yourself. Commented Aug 19, 2010 at 22:44
  • 1
    @Stephen: That link makes no sense (that person obviously fails to understand the difference between C++ the language and implementations). I wish there were a super-delete button on the internet. In any case, dynamic, automatic, and static are storage durations. An automatic is the default, and objects with automatic duration will be destroys automatically (hence the name) at the end of their scope. Dynamic allocation is independent from scope, and you obtain a pointer to a dynamically allocated object via new (and friends.) If you never manually delete a dynamically allocated object... Commented Aug 19, 2010 at 22:56
  • 1
    @Stephen I recommend: stop. Read a book about C++. You will not get this stuff right by trial and error. Commented Aug 19, 2010 at 22:57
  • ...its lifetime will never end, resulting in a leak. (You can end the lifetime of a dynamically allocated object via delete (and friends.)) In C++, automatically allocated objects are (on a typical platform) quickly allocated because they are on the stack, and much safer. (Impossible to leak!) Contrarily, dynamic allocation tends to be slower, and is easy to mess up. Modern C++ uses automatic objects to "own" objects, and will automatically free them when it's time. (They pass ownership around, or share it.) In any case, you need to start from the beginning. Get a good book and read. Commented Aug 19, 2010 at 22:58