*
:
> Alf P. Steinbach wrote:
> > * Thomas Tutone:
> > >
> > > Bob Hairgrove wrote:
> > >
> > > Yes - My answer was incorrect. Sorry about that.
> >
> > Well no. Your follow-up explanation was incorrect, but your original
> > answer was just incomplete.
> >
> > Declaring the destructor protected in ABC is indeed a Good Thing To Do,
> > because it means instances of the class _have_ to be dynamically
> > allocated -- a standard compiler won't then allow anything else.
> >
> > Of course then the client code must be offered some means to deallocate.
> > A bad way is to provide a delete-yourself public member function. A
> > general and good way is to define a common destruction function
> >
> > template< typename T > callDelete( T* p ) { delete p; }
> >
> > and make that function (as well as std::auto_ptr) a friend of the class.
>
> What about the case of custom allocators? Here the protocol for an
> allocator provides a member template for deleting objects allocated
> from a 'MyAllocator' (e.g., via placement-new). IME, this is a much
> more useful idom than 'callDelete', it does not require friendship, and
> it contradicts the "principle" that virtual destructors should be
> protected.
>
> class MyAllocator {
> public:
> virtual ~MyAllocator();
>
> void *allocate(std::size_t size) = 0;
> void deallocate(void *buffer) = 0;
>
> template <typename TYPE>
> void deleteObject(TYPE *object) {
> object->~TYPE();
> deallocate(object);
> }
> };
You're not making sense to me.
First, there is no "principle" that's based on virtuality of destructor.
There is a technique to ensure dynamic allocation. Dynamic allocation +
inheritance generally implies virtual destructor, but not the other way
around.
Second, the existence of an an allocator class somewhere does not
prevent client code from declaring a static, local or member variable of
any type, and a placement allocation function doesn't, either.
Perhaps you meant to write something more, e.g. an example of a class
using that allocator, where somehow that class was restricted to dynamic
allocation (no such mechanism obvious in what you write), or perhaps
where that class encapsulated all dynamic allocation inside a
value-semantics interface, like the standard container classes (comment
about virtual destructor makes no sense then)?
Btw., allocators are mostly difficult to use properly, and I think in
the above the destructor should offer the no-throw guarantee, and the
allocate member should have typed result, centralizing the casting, like
std::allocator, and the deleteObject function should absolutely not be
templated (ever heard of type safety?); template the class instead.
Cheers,
- 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?