Re: Hidden Features and Dark Corners of C++/STL
ironsel2000@gmail.com (puzzlecracker) wrote (abridged):
But what are the most hidden features or tricks or dark corners of
C++/ STL that even C++ fans, addicts, and experts barely know?
It's hard to know which tricks are obscure enough to count. I find
declarations in if-statements useful:
if (Object *p = get_object())
p->use();
It's concise, and also helps minimise the scope of p, making it harder to
accidentally use it when it is undefined or NULL. It's convenient enough
that I sometimes adding bool conversions to my own classes in order to
use it:
if (Object o = get_object())
o.use();
The correct way to do that is itself probably a trick. Simply adding
operator bool() is a bad idea because it enables conversions to int,
which are scarily general. There is more on this here:
http://www.artima.com/cppsource/safebool.html
std::partition can be handy if you are dealing with raw pointers (is this
dark enough?) Std::erase() will overwrite some pointers with other
pointers, which can lead to memory leaks, but with std::partition every
pointer is preserved.
void predicate_delete( std::vector<int *> &v ) {
std::vector<int *>::iterator i = std::partition(
v.begin(), v.end(), predicate() );
for (std::vector<int *>::iterator j = i; j != v.end(); ++j) {
// delete *j would leave an invalid value in the vector,
// so remove it first.
int *p = *j;
*j = 0;
delete p;
}
v.erase( i, v.end() );
}
Not everyone knows that URLs are valid C++ syntax. Admittedly that's
largely because it's not very useful:
int main() {
http://www.boost.org/
return 0;
}
-- Dave Harris, Nottingham, UK.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]