- This topic has 0 replies, 1 voice, and was last updated 19 years, 9 months ago by .
Viewing 0 reply threads
Viewing 0 reply threads
- The forum ‘C Programming’ is closed to new topics and replies.
Home › Forums › C Programming › Use STL containers instead of C arrays
When using C++, you should always strive to use STL containers like std::vector and std::list instead of ordinary C arrays.
Consider this example:
1 2 3 4 | <br /> int* array = new array[size];<br /> doSomething(array);<br /> delete[] array; |
All is fine, until doSomething() is changed to throw an exception. If doSomething throws, we will have a memory leak.
The correct way of doing this is:
1 2 3 | <br /> vector array(size);<br /> doSomething(); |
If doSomething() throws an exception now, no memory will be leaked.
This is just one of the reasons to use STL containers instead of C arrays. STL containers are much less error prone, more robust and easier to use.