-1

i,m trying to create pointer to pointer List

list<ObjectClass*> *lst_testList;

and trying to use it this way

void FunctioningClass::functioningMethod()
{
    ObjectClass *object = new ObjectClass();
    object->i_testing = 234;
    lst_testList->push_back(object);
    object = lst_testList->front();
    cout<<object->i_testing;
    std::getchar();
}

I can build the program. But when i run it,it gives me this error.

Unhandled exception at 0x012885DA in ConsoleApplication7.exe: 0xC0000005: Access violation reading location 0x00000004.

notice that when i create list like this

list<ObjectClass*> lst_testList;

and use it like this,

lst_testList.push_back(object);

it didn,t give me any error.

Yasitha Bandara
  • 1,093
  • 1
  • 11
  • 18

2 Answers2

3

list<ObjectClass*> *lst_testList is a pointer to a list of ObjectClass pointers. In order to use it you either need to allocate it first or (as you already found out) uselist<ObjectClass*> lst_testList (which is a list to ObjectClass pointers) .

Yasitha Bandara
  • 1,093
  • 1
  • 11
  • 18
Ton Plooij
  • 2,493
  • 10
  • 15
1

Such list<ObjectClass*> lst_testList; variable is default-initialized.

For pointer list<ObjectClass*>* lst_testList; default initialization is not performed. Proper initialization for it is:

list<ObjectClass*>* lst_testList = new list<ObjectClass*>();

or

list<ObjectClass*>* lst_testList = NULL;

It depends on your goals.

Nikita
  • 5,966
  • 2
  • 23
  • 35
  • Are there any advantages & disadvantages between two methods? – Yasitha Bandara Aug 24 '16 at 07:34
  • @YasithaBandara It's hard to say. It depends on architecture of your application (e.g. on `lst_testList` visibility). If it's global variable you can create single instance `new list()` and use it over the application. If it's a field of `FunctioningClass` you can initialize `lst_testList` to `NULL` and create an instance `new list()` later when it will be needed. – Nikita Aug 24 '16 at 07:46
  • @YasithaBandara General approach is to always initialize pointers to some value. `NULL` will guarantee predictable behavior. It's easy to understand why pointer is `NULL`, but very hard to debug unpredictable behavior of [dangling pointer](https://en.wikipedia.org/wiki/Dangling_pointer). – Nikita Aug 24 '16 at 07:48