| ||||||||||||||||||||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Memory & arrays - Should I vector.clear()?
Say I have a class with some vectors as private fields. In my program, all of these vectors will contain pointers created by "new" mechanism, therefore in the class destructor I'm deleting all the pointers. My question is, is there any point in clearing the vector afterwards, ie vector.clear() ? Or will that be taken care of by the Vector class destructor?
Thanks |
|
#2
|
||||
|
||||
|
The vector destructor will take care of that. Instead of manually deleting all the pointers (which is good, many people forget that), you could also consider storing smart pointers in your vector. That way you do not need to clean up any memory manually.
__________________
There is no such thing as C/C++, you either program C or C++ |
|
#3
|
|||
|
|||
|
Haven't thought about smart pointers..actually the part of the program that handles the pointer creation is out of my hands (it's a hw assignment, the main is already given as-is). Anyway thanks.
|
|
#4
|
|||
|
|||
|
Another question
It's got nothing to do with the last one, it's just that I don't feel comfortable opening a new thread for each question.
So, is there a reason why not to use a const reference when writing a constructor? For example: Code:
Class A
{
A(const std::string& dname) : name(dname) ...
};
Should I do it like this every time, for not copying objects for nothing (the &) and for not changing what I'm not supposed to (the constness)? |
|
#5
|
||||
|
||||
|
Well you shouldn't do this every time. There are not many 'always-do-this' rules in programming (that's what makes it interesting?).
But yes, I find myself writing parameters as const reference quite often, almost always for strings. If you're only going to read a parameter then a const reference is most often the 'best' way to go. For primitive types like int, float, and bool I do not pass const references though, but a copy. Which comes down to the same anyway: you make a copy so you're not changing the original (no need for const), and you might even be slightly faster since you do not have an extra indirection, ymmv. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Memory & arrays - Should I vector.clear()? |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|