-1

normally the object new bar() will be automatically destroyed after exiting the scope why I have to do a delete pBar then ?

    class bar{
      public:
      bar(){}
      //...
     };

    class foo{
        public:
        foo(){}
        void createBar(){
            bar* pBar = new bar();
            // stuff..
            delete pBar;
        }// why should I use delete and the pBar should be delted after the end of the scope ?
    };

also if in the function createBar() I add pBar pointer to a vector of another class. the vector has only point to the pBar (not owner). in this case where do I put the delete ? because if I keep it where it is it will delete the pointers then my manager vector will point to nothing .. if I use the delete inside the manager class, so I will delete an object inside a non-owner class ?!

PS: I know that I can use smart pointer, but I just want to understand this point

void createBar(){
    bar* pBar = new bar();
    // stuff
    manager::add(pBar);
    delete pBar;
 }

class manager{
   public:
   manager(){}
   void add(bar* p){
       vFoo.push_back(p);
   }

   private:
   std::vector<bar*> vFoo;
}
arturo
  • 11
  • 1
  • 11
    _"the object new bar() will be automatically destroyed after exiting the scope"_ That's not correct. Local variables will be destroyed, like your pointer. But destroying a raw pointer does not affect the object it points to. That's how you get a memory leak. – Drew Dormann Dec 17 '21 at 15:57
  • 1
    "normally the object new bar() will be automatically destroyed" where did you get this from? – 463035818_is_not_an_ai Dec 17 '21 at 15:57
  • 3
    Ideally you should not be using `new` or `delete` at all. But yes, if every `new` is not matched with a `delete` on all exit paths, then you can have a memory leak. – NathanOliver Dec 17 '21 at 15:57
  • Just use `bar myBar;` if you want it to autmatically get destroyed when it goes out of scope – Kevin Dec 17 '21 at 15:58
  • in your last code you store a pointer to some object and then immediately destroy the object. The pointer in the vector is useless. Simply don't use raw pointers – 463035818_is_not_an_ai Dec 17 '21 at 15:58
  • *in this case where do I put the delete ?* -- You designed the code -- you should know where to place the `delete` call to match your design and not to create memory leaks. No one, except yourself, would know where *exactly* you need to do this. That's the responsibility you bring on yourself when you decide to handle dynamically allocated memory yourself. – PaulMcKenzie Dec 17 '21 at 15:58
  • It looks like a broken attempt at a factory. – sweenish Dec 17 '21 at 16:07
  • @DrewDormann how writing `delete pBar` will destroy `bar()` object ?? according to the writing (delete pBar) it's a pointer. and supposing I'm not going to do the delete in the `createBar()` function but rather in the `manager` in this case I'm going to delete `vFoo` in this case the object `bar()` will be destroyed ? if yes then I have to follow who points to my object those that will be destroyed after the scope haliluia and the last delete I have to do it myself to ensure the release of the memory, correct ? – arturo Dec 17 '21 at 16:18
  • q.v. [storage duration](https://en.cppreference.com/w/cpp/language/storage_duration#Storage_duration). *Automatic storage* is destroyed after exiting the object's scope; object lifespan is managed automatically. *Dynamic storage* (e.g., using `new`) is destroyed explicitly by `delete`; object lifespan is managed manually. – Eljay Dec 17 '21 at 16:27
  • @arturo it's probably a good time for [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). An introductory chapter should explain C++ memory management. Stack Overflow does not work well at reproducing introductory book chapters. – Drew Dormann Dec 17 '21 at 16:35
  • @arturo You are correct that `pBar` is a pointer. Pointers are commonly used to identify to operators and functions what objects you want them to operate on. It can be used to point to the object that you want `delete` to delete. The code `delete pBar;` doesn't mean to delete `pBar` itself. It uses `pBar`'s value to identify to `delete` what object to operate on. – David Schwartz Dec 17 '21 at 17:10
  • @463035818_is_not_a_number It's pretty clear he is misunderstanding the difference between objects being freed after they leave scope. There's no reason to be derisive toward him. – user904963 Dec 24 '21 at 23:05
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Dec 24 '21 at 23:08

2 Answers2

1

Nowadays you should never ever use new() or delete(). (Of course there are exceptions to to this, but these are very rare.)

Use the appropriate class which encapsulates the memory handling for you, like shared_ptr (https://en.cppreference.com/w/cpp/memory/shared_ptr), or unique_ptr (https://en.cppreference.com/w/cpp/memory/unique_ptr).

Andreas Florath
  • 4,418
  • 22
  • 32
  • Yes. I try to never use `new`. There are exceptions, but always reach for `std::make_unique` first and your life will be better. In this case it’ll mean `std::vector> vFoo;` and some `std::move` but you won’t have to worry about leaks. – Ben Dec 18 '21 at 01:01
  • You use `new` when you use a smart pointer. – user904963 Dec 26 '21 at 20:36
0

How manager is used isn't exactly clear, but if a single manager object holds the pointers and no one else has them, you should write a destructor that calls delete on each pointer once your manager goes out of scope or once a pointer to manager has delete called on it.

Also, you need to create a manager object before using manager::add. As it is now, the code should generate compiler errors. For example,

manager m{};
m.add(pBar);
user904963
  • 1,520
  • 2
  • 15
  • 33