-3

You cannot return an address of something that is defined locally so you must allocate memory on the 'heap' for this element to be placed so that other functions in the program may access it. Can someone explain this in more detail please.

MyClass* myFunc() 
{
    MyClass* pMC = new MyClass;
    return pMC;
}

What is the purpose of the * in the function name? What is this indicating? I realize that there is a creation of a pointer of type MyClass and it points to a new allocation on the 'heap' of this object. I just fail to understand what exactly the usefulness of this is.

trincot
  • 317,000
  • 35
  • 244
  • 286
beeks
  • 197
  • 1
  • 1
  • 5
  • You need a *dynamic object*, whose lifetime you must manage manually, and `new` creates such a manual object. Throw away the ebook while you're at it, though :-) (I guess you'll have to `delete` it.) – Kerrek SB Feb 12 '12 at 19:52
  • possible duplicate of [What is a Memory Heap?](http://stackoverflow.com/questions/2308751/what-is-a-memory-heap) – Nicol Bolas Feb 12 '12 at 19:54
  • So, here, a dynamic object is being created called MyClass? How do you manage the lifetime of this object? – beeks Feb 12 '12 at 19:55
  • Nice, Ill check that link out. When I typed in the name there were no similar results so I submitted the question. – beeks Feb 12 '12 at 19:56
  • @bden you manage the lifetime by using `new` to begin the lifetime and `delete` to end it. – Seth Carnegie Feb 12 '12 at 19:56
  • @bden: You have to manage it manually if you use a raw pointer like this (i.e. you have to `delete` it after it's no longer needed). See the answer for the better way of using a smart pointer instead. – Niklas B. Feb 12 '12 at 19:58
  • If you think of yourself as a dummy, you will never be anything else. – Kerrek SB Feb 12 '12 at 20:01

1 Answers1

2

What it means is that the object will always exist until it is explicitly destroyed.

Handling this destruction yourself is an immensely bad idea for a large number of reasons, and there exist a number of schemes that automatically clean it up at various points- unique or shared ownership, for example. This means that code which uses new directly is very bad, and triply so for new[], delete, or delete[].

In unique ownership, there is one pointer (std::unique_ptr<T>) which owns the object, and when it is destroyed, the object is destroyed. This is move-only. In shared ownership, when any (std::shared_ptr<T>) which points to the object is alive, the object remains alive. When the last one is destroyed, the object is also destroyed.

Puppy
  • 144,682
  • 38
  • 256
  • 465