* Alfonzo Morra:
MyClass::foo ( const std::string str) {
char* s = str.c_str() ; //<- presumably a call to calloc/malloc
// behind the scenes ...
...
//Do I need a free(s) here to free memory allocated ?
}
First, to clear up some remarks made by another poster:
* Adding 'const' to pass-by-value can be helpful to detect the
common '=' instead of '==' typo. But be aware that the 'const'
does not, in this case, affect the function signature. Also,
it may be more efficient to pass by reference, i.e.
std::string const& str
and that is how it's usually done.
* The declaration of 's' should be
char const* const s = str.c_str();
The first 'const' refers to the contents of the string; you can
get away without it only because of an old C compatibility feature
stemming from the time before 'const' was introduced. The second
'const' refers to the pointer itself, ensuring that this pointer
is not reassigned to point to something else.
* The 'const's have nothing to do with memory allocation/deallocation.
The pointer you obtain is valid until you change the contents of 'str'; it
is the 'str' object that is responsible for deallocation, if any is needed.
Since 'str' is 'const' and by value a change of 'str' won't happen, so the
pointer is guaranteed to be valid till the end of the function body.
When you pass by reference you run the risk of aliasing, that in some way
the code may change the contents of 'str' via some non-'const' reference,
e.g. a global reference, and in that case the pointer can be become invalid.
However, ordinarily that's not a problem. Strings are simply not used in
ways that can ordinarily cause aliasing, and anyway, globals are Evil... ;-)
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?