lists and new objects

hello again

please consider the small piece of code below?

bunnyList.push_front( new mutantType ("Black"));

It simply creates a new pointer to a mutantType object and stores it in a list called bunnyList. Is there any special considerations when doing this i should take into account?

The parameter "Black" is just a string that the constructor (obviously with a parameter) uses to set one of the many member variables to "Black". It is not reporting an error when compiling or anything like that,but still behaving strange , in that the member variable is not being set to "Black". The problem probably lies elsewhere in the code but i wondered if what i've done might present a more fundamental problem??
Is there any special considerations when doing this i should take into account?

Yes, since you would have to delete the object manually when removing it from the list, you should use ptr_list instead.

in that the member variable is not being set to "Black".

Then the problem is in the constructor.
okay.. that's interesting because at periods in my program i will need to to delete elemets from the my lists.
Is ptr_list part of a standard library?, or do have to download it from somewhere? If so will it have the same functionality as 'List' in other respects?.

Excuse my ignorance, i am fairly new to lists
If you just remove the pointer from the list without calling delete on it, you'll have a memory leak.

Mike200 wrote:
It simply creates a new pointer to a mutantType object and stores it in a list called bunnyList

Actually, it creates an object and returns a pointer to it. Thus, if you lose the pointer without calling delete to deallocate the object, the object will still exist in memory, and you won't be able to access it.
Last edited on
I gather that, since you want to store pointers in the list, you want to use polymorphism. I guess you have a base Bunny class and a derived MutantBunny class that behave slightly differently. For this particular exercise, maybe it would be better to just have a Bunny class and a bool data member indicating if it's a mutant or not. Then, you can use a list of Bunnies (not pointers to Bunnies) and you don't have to worry about memory deallocation.
Is ptr_list part of a standard library?, or do have to download it from somewhere? If so will it have the same functionality as 'List' in other respects?.

Unfortunately, it's not part of the standard library, but there are many implementations. boost has one, for instance.
You can assume that a proper implementation provides all the functionality std::list has.
Last edited on
Topic archived. No new replies allowed.