Re: virtual destructor 101
On 10/16/2010 10:26 PM, Bronek Kozicki wrote:
On 16/10/2010 01:27, Dragan Milenkovic wrote:
But... making a virtual destructor protected actually tries to
enforce a specific memory management, or at least prohibit
the trivial "delete by pointer to base" interface which is completely
valid type of memory management. IMHO this is not something one should
decide or put into an interface describing a Stack.
not at all. Choice between protected/public destructor does not, in any
way, constraint implementation classes. It does, however, constrain user
of interface class and as such it carries important information "user of
an interface is not an owner".
I disagree. I'll answer about the second part - "user of an interface
is not an owner". I guess you mean an owner of the object? Because it
can or cannot be true, depending on the interface...
std::unique_ptr<Foo> CreateFoo();
.... I'd say that the user becomes the owner of the object. In other
designs this may be different.
And now for your claim that choosing between public/protected destructor
doesn't constrain implementation. I'll have to nit-pick a bit. My claim
was not that it constrains classes implementing the interface,
but that it constrains memory management related to that
implementation. For example:
class Stack {
protected:
virtual ~Stack() = 0;
public:
/* bla bla */
};
Now I cannot design a factory function returning std::unique_ptr<Stack>,
nor can I design a function that returns a raw pointer and give
ownership to the user (actually I can do this, but the user cannot
call "delete" so it doesn't work). So I'm constrained, although
this has nothing to do with the concept of Stack. Should there
be two Stack interfaces? One for those who want to expose "delete"
and one for those who want to hide it? I'd say "no"...
So my statement is that virtual destructor doesn't fit well into
the memory management of C++... because it has to be defined in
a wrong place related to a feature that it supports
(hope it came out right).
Maybe banning "delete" for abstract classes in favor of
shared_ptr/unique_ptr would solve the problem, but how
could we implement unique_ptr then? (shared_ptr would
still work). I don't know, just thinking out loud...
--
Dragan
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]