Re: unfamiliar idiom
* d04rp@student.lth.se:
I have read alot of C++-books the past two years but the following
idiom has never been introduced to me earlier.
Is this nonsense or does it makes sense? Any pros and cons?
Biggest con that this scheme adds O(n^2) behavior for destruction of a set of
Widget instances.
One might almost suspect that this is code from unmentionable company X...
Second con, that in theory you might run into the static initialization fiasco
problem (see the FAQ).
I think it could be applicable when this kind off runtime information
about all living objects of some class is needed.
class Widget {
public:
static vector<Widget*> everyone;
Widget() {
everyone.push_back(this);
}
~Widget() {
everyone.erase(find(everyone.begin(), everyone.end(), this));
}
};
vector<Widget*> Widget::everyone;
Try this instead:
<code>
#include <set>
class Widget
{
public:
static std::set<Widget*> all;
Widget() { all.insert( this ); }
~Widget() { all.erase( this ); }
};
std::set<Widget*> Widget::all;
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
using namespace std;
{
Widget a, b, c;
ostream_iterator<Widget*> oi( cout, "\n" );
copy( Widget::all.begin(), Widget::all.end(), oi );
}
}
</code>
Note that here the ease() operation is guaranteed O(log n).
By the way, please don't post tab characters, but instead convert tabs to spaces
before posting.
Cheers, & hth.,
- Alf
--
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?
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]