D
davidrubin
Alf said:* Thomas Tutone:
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);
}
};