0

I am learning c++ and not totally sure on how to insert and remove certain or all items in a list properly. This is what i am doing.

The struct

struct  _STRUCT_TYPE_
{
    int nReference
    char[128] strAddress
};

Defining the list

std::list<_STRUCT_TYPE_> m_ListExample

Inserting into the list

_STRUCT_TYPE_ pStruct;
pStruct.nReference = nVar1;
pStruct.strAddress = strVar2
m_ListExample.push_back(pStruct);

Clearing the list

m_ListExample.clear();

Am i doing every correctly? could something better be done? i am interested.

user2142260
  • 31
  • 1
  • 3
  • 2
    You're using a [reserved identifier](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). And that example does not compile. – chris Jul 10 '13 at 08:37
  • 1
    That looks OK as far as the list is concerned, if you really need to explicitly clear it. The list will be cleared anyway when it goes out of scope. – juanchopanza Jul 10 '13 at 08:38
  • By calling the .clear() method over your list you are removing all elements from the list container (which are destroyed), and leaving the container with a size of 0. So this seems quite good; relax... For more information on manipulating lists look [here](http://www.cplusplus.com/reference/list/list/) – NREZ Jul 10 '13 at 08:56

1 Answers1

0

Your std::list is stack allocated, meaning it will be cleared automatically.

If you had

int x;

there would not be much you could do because it is stack allocated, however if you had

int* x = new int;

or

int* x = malloc(sizeof(int));

you would face to call

delete x;

or

free(x);

Stack allocation is generally faster but if you really wanted to alter your code so that the list is heap allocated, and that you can be sure the memory is deallocated, you can do the following:

struct  _STRUCT_TYPE_
{
    int nReference
    char[128] strAddress
};

std::list<_STRUCT_TYPE_>* m_ListExample;

int main()
{
    _STRUCT_TYPE_ pStruct;
    pStruct.nReference = nVar1;
    pStruct.strAddress = strVar2
    m_ListExample->push_back(pStruct);

    //when done
    m_ListExample->clear();
    delete m_ListExample;

    return 0;
}
Nico Cvitak
  • 471
  • 4
  • 7