|
Boost : |
From: Jeffrey D. Paquette (paquette_at_[hidden])
Date: 2000-04-29 08:06:11
I've been following this group for a few months now and have seen several
variations of scoped utility classes fly by (shared_ptr, deferred_value,
etc) and it seems that all of these classes, including a few that I've
written have one drawback that can lead to misuse: they all can be
dynamically allocated, thus bypassing the intent of the class.
So, in the spirit of noncopyable, here is a first cut at nonallocatable:
class nonallocatable {
private:
// single instance new and delete
void *operator new(size_t);
void operator delete(void *);
void *operator new(size_t, const std::nothrow_t&) throw ();
void operator delete(void *, const std::nothrow_t&) throw ();
// array new and delete
void *operator new[](size_t);
void operator delete[](void *);
void *operator new[](size_t, const std::nothrow_t&) throw ();
void operator delete[](void *, const std::nothrow_t&) throw ();
// placement new and delete
void *operator new(size_t, void *) throw ();
void operator delete(void *, void *) throw ();
void *operator new[](size_t, void *) throw ();
void operator delete[](void *, void *) throw ();
};
The idea is to derive scope-helper classes from nonallocatable, thus
preventing the misuse of these classes, like so:
void leak()
{
shared_ptr<int> *p = new shared_ptr<int>(new int);
}
test code:
class test : private nonallocatable {
public:
int x;
};
class test2 : test {
};
int main (int, char **)
{
test *p = new test;
test2 *p1= new test2;
test *p2 = new test[4];
int q;
test *p3 = new(&q) test;
test2 *p4 = new(std::nothrow) test2;
return 0;
}
Tested with VC6.0sp3 and egcs-2.91.66 (Redhat6.1)
I'm sure I'm going to get educated here :)
-- Jeff Paquette paquette_at_[hidden], paquette_at_[hidden] http://www.atnetsend.net
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk