1

When should i use the pointer and when not? Whats the better Way? Must i delete the cat object of the pointer at the end of the programm?

Example:

cat piki;
piki.miao();
cat *piki2 = new cat();
piki2->miao();
mullek
  • 2,131
  • 4
  • 17
  • 12
  • possible duplicate of [Proper stack and heap usage in C++?](http://stackoverflow.com/questions/599308/proper-stack-and-heap-usage-in-c) – Luc Touraille Sep 08 '10 at 15:59

8 Answers8

8

Whenever possible try to avoid creating the object using new (i.e. on heap) as you would have to do memory management yourself (or at least you need to use smart pointers). If you allocate the object on stack (i.e. cat piki;) the memory allocated for the cat object is automatically released when the piki goes out of scope. This doesn't happen with piki2, you need to explictly do delete piki2; to release memory.

Naveen
  • 74,600
  • 47
  • 176
  • 233
  • This answer is poorly phrased. A better answer is: do not use new unless you need to. – HandyGandy Sep 08 '10 at 12:51
  • I'd say: do not use new unless you know why you use it – Nikko Sep 08 '10 at 14:30
  • @HandyGandy When I read Naveen's answer I understand what he want's to tell me. When I read your answer I have tons of questions which are mostly explained in Naveen's answer. – Davlog Aug 31 '13 at 14:26
1

Creating an ojbect with or without a new depends on where you are using the object. An object of your class can be created without a new if you are using it within a function, or a block so that the destructor automatically gets called once your object is out of scope.

If you want your object to be used in multiple methods or you want to return the object from a function, then you need to create the object using new, and also make sure you delete it properly.

KhanS
  • 1,167
  • 2
  • 12
  • 27
1

To answer "Must i delete the cat object of the pointer at the end of the programm?" which I haven't seen in other answers:
When the program ends, technically speaking, you often need not (see also remark from Tony) delete objects you allocated with new, because most os'es will clean up after you. (Notice the "most", MsDos (I don't know which versions) was an example were that didn't happen, so you had to reboot when running these programs).
However, it is considered bad practice not to delete what you have newed, because programs tend to grow and what was "acceptable" before might suddenly lead to a memory leak, possibly resulting in an unstable system.

examples where deleting may not be done (I am not sggesting that in these cases you shouldn't care):

  • when using Singletons, to avoid dependency issues in destructors.
  • in multi-threaded systems, some threads holding any resources may be halted without cleaning up.

In simple cases of course, prefer allocating without new as suggested in other answers.

stefaanv
  • 14,072
  • 2
  • 31
  • 53
  • 5
    "In most cases, you must not delete objects you allocated with new,..." The only places I worked that I would not be fired for following this advice are places where I was the only programmer. In those places no one would know I am doing something incredibly stupid. – HandyGandy Sep 08 '10 at 09:46
  • This is full of serious misconceptions. new and the heap memory it's allocated are about controlling object lifetime. The optimal behaviour is normally to only have objects around when the data in them is useful. new is a mechanism to decouple memory allocation from the stack, so that the lifetime of data isn't tied to function entry and exit the way stack variables' lifetimes are. Other things you say are correct: one option with Singletons and some resources is to let the OS clean up, and not using new should always be the preference if it's still a natural fit for the lifetime required. – Tony Delroy Sep 08 '10 at 11:00
  • @HandyGandy: you may read the complete answer before jumping to conclusions (or isn't that a reason to get fired): I was not giving advice, I was merely technically answering the question which was not answered by others: technically speaking, you don't have to clean up resources when ending a program when working in a sane OS (because it knows about insane applications and also because crashing applications should not take the OS with them. But I will edit to make that aspect clearer. – stefaanv Sep 08 '10 at 11:08
  • @Tony: there may be misunderstandings in your remark, because I don't see the connection between your remark and my response. Is it a different understanding of "at the end of the program", which I understand as "technically speaking, must I make sure that everything is cleaned up before ending?". – stefaanv Sep 08 '10 at 11:14
  • It is actually quite funny. I do know about cleaning up resources and using RAII, but just the possibility of having a new without a delete seems to stop people from reading the complete answer... – stefaanv Sep 08 '10 at 11:20
  • @stefaanv: have re-read your answer / I'd missed that you were trying to address only the one specific aspect of the original question re cat and the program ending. Fair enough. Then, the only issue I have with your answer is in "program ends, technically speaking, you *must not* delete objects you allocated with new"... where "must not" is totally wrong. "often need not" would be correct, provided the destructor doesn't need to do other things like flush buffered output, send orderly logoff messages, release shared memory areas or locks therein etc.. – Tony Delroy Sep 09 '10 at 01:15
0

The piki object will be autodeleted when the current scope is closed.

piki2 must be explicitly deleted.

delete piki2;
  • 3
    This is not an answer to the important part of the question! – Nikko Sep 08 '10 at 10:03
  • 1
    The question is too broad to be simply answered. You can write a book about the topic. What was answerable, I answered it. –  Sep 08 '10 at 10:05
0

This is purely specific to your requirement. One reason to use objects directly would be if you know how many objects you need. However if you are not sure how many objects you will create you can create objects using new operator each time one is required to be created.

But in case you you use a pointer like you have done

cat *piki2 - new cat();

Then as you have mentioned you need to delete the pointer once its use is over.

delete piki2;
ckv
  • 10,539
  • 20
  • 100
  • 144
0
cat *piki2 = new cat();
piki2->miao();

This is several forms of fail. For example, what if miao throws an exception? You should always use a self-releasing pointer for resources. Objects created with operator new are quite slow to create and slow to access and manage, plus additional memory overhead, so you really should use the first form wherever possible.

Puppy
  • 144,682
  • 38
  • 256
  • 465
0

Use smart pointers where you can. Use boost smart pointers library.

http://www.boost.org/doc/libs/1_44_0/libs/smart_ptr/smart_ptr.htm

Davit Siradeghyan
  • 6,053
  • 6
  • 24
  • 29
  • 1
    Actually, more correct would be "Use smart pointers where you use new to allocate your object". Automatic variables (stack) do have their use. – stefaanv Sep 08 '10 at 11:28
0

As Developer Art has said you could write a book about this topic. Especially if you make lists of heuristics as is sort of asked for.

However, a few rules will go a long way.

A factor to consider is that stack allocated instances of cat will not be treated polymorphically. For an object to be treeated polymorphically it must be represented by a pointer or a reference.

Any object that is no longer needed should be freed ASAP, or set on the trail of automatic deletion ( auto_ptr or some sort of reference counted smart_ptr ). Keep in mind that the memory is not just freed, the objects destructor is called -- and there is RIAA.

You also have to keep in mind that if an object is to be passed around a lot, and has an expensive copy constructor then using an object rather then a pointer is going to invoke a large cost.

Finally you need to ask yourself how long an object has to live. If it needs to live beyond the local scope then it will most likely need to be a pointer.

HandyGandy
  • 660
  • 2
  • 6
  • 15