0

If I created a pointer by new keyword, and I didn't delete it. Will it be automatically destroyed when its scope ends or when the whole program ends?

bassel27
  • 31
  • 5
  • Scope ends? No. Program ends? That's up to your operating system. – Drew Dormann Mar 08 '21 at 19:00
  • It will not get deleted when it leaves the scope, it gets "destroyed" when the program end because your OS is cleaning it up – RoQuOTriX Mar 08 '21 at 19:01
  • If it did get automatically deleted, it would have far less utillity. – StoryTeller - Unslander Monica Mar 08 '21 at 19:20
  • 5
    Your question asks about the pointer but it sounds like what you really want to know is what happens to the object it points to. The pointer is destroyed since it goes out of scope, but the object it points to still exists. – David Schwartz Mar 08 '21 at 19:29
  • 1
    Objects created by the `new` operator don’t have scopes. That’s the point. So your code has to manage their lifetimes. – Pete Becker Mar 08 '21 at 21:24
  • 1
    While learning about c++, it is a good idea to learn how `new`/`delete` works. But after that you are supposed to use container classes and smart pointers, and never ever use `new`/`delete` again. The added benefit is that you probably never have to write destructors or copy/move contstructors again. – HAL9000 Mar 08 '21 at 21:34

0 Answers0