Re: unfamiliar idiom
<d04rp@student.lth.se> wrote in message
news:7f610cc2-d0a0-4eb9-9e9d-1de301825652@i12g2000prf.googlegroups.com...
[8<8<8<]
Is this nonsense or does it makes sense?
It makes perfectly sense.
Any pros and cons?
If there are any Widget objects created as global object (non local, static
storage duration) the "everyone" container may or may not be constructor
when the Widget constructor is executed.
In that case
Furthermore often there is no need to have "everyone" as part of the
declaration of Widget (it's a bad idea to have it publicly accessable
anyway), but instead have it as a global variable in unnamed namespace in
the cpp-file. This increases encapsulation.
Combined this means something like (not test compiled and a few details
missing):
HPP-file:
class Widget
{
public:
Widget();
~Widget()
// ... whatever
private:
Widget(const Widget); // prohibit copy-construction
};
CPP-file:
namespace
{ // start of unnamed namespace
// vector or set - depending on needs
vector<Widget*>* everyoneWidget;
Widget::Widget()
{
if(!everyoneWidget)
everyoneWidget = new vector<Widget*>;
assert(everyoneWidget);
assert(everyoneWidget->end() == find(everyoneWidget->begin(),
everyoneWidget->end(), this));
everyoneWidget->push_back(this);
}
Widget::~Widget()
{
assert(everyoneWidget);
assert(everyoneWidget->end() != find(everyoneWidget->begin(),
everyoneWidget->end(), this));
everyoneWidget->erase(find(everyoneWidget->begin(), everyoneWidget->end(),
this));
if(everyoneWidget->empty()) {
delete everyoneWidget;
everyoneWidget = 0;
}
}
} // end of unnamed namespace
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]