0
{
    //i want remove it after using
    struct pTemporary001 {
        string name;
    };
    pTemporary001 *pTemporary001_var = new pTemporary001;
    ConsoleQuestioner<pTemporary001>("TEST TEXT", pTemporary001_var, [](string *name, pTemporary001 *temp) {
        temp->name = *name;
    });
    cout << "test : " << pTemporary001_var->name << endl;
    delete pTemporary001_var;
}

I want to remove for declared structure(pTemporary001) after using.
It'll be automatically collect when current level capsules completed? or is it collected at end of program?

  • 2
    C++ does not have any garbage collection. Why are you using `new` at all? (Take a look at the [book list](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)). – molbdnilo Aug 28 '20 at 15:46
  • Take a look at the concept of `destructor` and `smart pointers`. It'll help you. – John Park Aug 28 '20 at 15:51
  • In the code snippet provided, you could use an *automatic* variable instead of a *dynamic* variable. If you are going to use a dynamic variable, I recommend using `auto pTemporary001_var = std::make_unique;` and avoid `new` and `delete` altogether. – Eljay Aug 28 '20 at 15:51
  • @JohnPark Thank you sir – lIIlIllIIlllIIlI Aug 28 '20 at 15:54
  • @molbdnilo Thanks. this is just part of practice code – lIIlIllIIlllIIlI Aug 28 '20 at 15:54
  • The concept of garbage collection, even if you would implement it in C++, doesn't make any sense applied to the type system. There is nothing *to* collect. – bitmask Aug 28 '20 at 15:59

1 Answers1

3

C++ doesn't have garbage collection.

And (unlike in dynamic languages) types do not consume memory in C++1, so there is no garbage to collect.

1 At least, not all types. Polymorphic types may require some amount of memory for RTTI and virtual dispatch. The shown class is not polymorphic. There is no way to release such memory within the program.

or is it collected at end of program?

The language specifies nothing about memory outside the duration of the program, but in practice all modern operating systems reclaim memory when a process is terminated.


General advice regarding the example: Avoid owning bare pointers such as pTemporary001 *pTemporary001_var, and avoid dynamic allocation when it is not needed. This looks like appropriate case for an automatic variable.

eerorika
  • 232,697
  • 12
  • 197
  • 326