Link to home
Start Free TrialLog in
Avatar of Makover
Makover

asked on

Erasing a vector contents

Suppose I have a class with 2 vectors (defined in <vector>) as members of the class.
Throughout the methods of the class I insert elements (strings that are read from a file, not allocated with "new") into these vectors. Should I erase all the elements of these vectors in the destructor of the class? If so - why? aren't these string allocated on the stack?

Same question for a vector I declared in one of the class methods. Should I call erase on this vector at the end of the method?

Thank You.  
Avatar of AlexFM
AlexFM

You don't need to do this because vector class destructor clears vector. Vector declared in class method may not be released as well.
But if you keep pointers as vector elements, you need to release all these pointers in destructor (or when the program exits the function).
Looks like you aren't really aware of what you are doing here. You most definately allocate new strings when inserting them into the std::vector. That's the reason why elements in a std::vector _need_ to have a copy constructor. The fact that you are reading strings from a file doesn't mean that you aren't creating new string objects either, unless you use some nifty memory-mapped file techniques.

A word of advice: When you are still new to a language, only use a subset that you are absolutely sure about how to use it. Always know what you are writing. With c++ this would most likely mean that you will be using it merely as a better c for a period of time.

.f
ASKER CERTIFIED SOLUTION
Avatar of Chase707
Chase707

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Makover

ASKER

Thanks AlexFM and fl0yd, All your answers were very helpful.