mardi 13 septembre 2022

Should I use dynamic allocations?

I have following c++ code (psuedo)

while(!fileEnd)
{
    rectD *rD = new rectD();
    symbol *sb = new symbol(rD);
    
    while( true )
    {
        if(closing brace)
        {
            sb->rD->isSymbol = true;
            sb->shapes[currentSymName] = *(sb->rD); // shapes is a std::map
            allSymbol[currentSymName] = sb; // allSymbol is a std::map
            break;
        }
        else
        {
            if(condition 1)
               sb->fun1();
            if(condition 2)
               sb->fun2();
        }
    }
}     
   

Now in rest of the program I use shapes and allSymbol map.

Here I want to ask,

Is new keyword necessary here ?

I know when we create object using new then it is created on heap memory and without using new, object is created on satck memory.

Heap memory lives until we delete it and stack memory gets deleted once function scope gets end.
In above code, Once the scope of above function ends I am no longer using *rD and *sb. But in through out program I am using std::map , shapes and allSymbols which contains *sb and *rD.

So I am confused, whether should I use new keyword or not ?
And if I have to use it, where should I release the memory ( using delete keyword) to avoid memory leak ?

Aucun commentaire:

Enregistrer un commentaire