private destructor and templates

B

Ben Voigt

I have a POD type with a private destructor. There are a whole hierarchy of
derived POD types, all meant to be freed using a public member function
Destroy in the base class. I get warning C4624. I read the description,
decided that it's exactly what I want, and ignored the warning.

Now I'm trying to inherit using a template. Instead of "destructor could
not be generated because a base class destructor is inaccessible", I now
have an error C2248 <name of base destructor> "cannot access private
member". Is this correct or a bug? I don't want the compiler to generate a
destructor for the base class, I won't declare any variables on the stack
and I will use the base Destroy function to deallocate it.

/**
** \brief Carries a request and any associated parameters.
**/
struct PNPEXPORT IConcurrentOperations::OpRequest abstract : OpMessage
{
...
private:
/**
** \brief Destructor, executes cleanup
**
** Calls FreeAgent to manage reference counting pAgent.
**
** Private visibility prevents declaration on the stack.
**/
~OpRequest()
{
FreeAgent();
}

public:
/**
** \brief Frees resources used by this request
**/
void Destroy( void )
{
delete this;
}
};

/**
** \param Base, should be derived from OpNotification or OpRequest
** and provide a default constructor.
**/
template<typename Base>
struct IConcurrentOperations::BufferedMessage : public Base
{...}
 
C

Carl Daniel [VC++ MVP]

Ben Voigt said:
I have a POD type with a private destructor. There are a whole hierarchy
of derived POD types, all meant to be freed using a public member function
Destroy in the base class. I get warning C4624. I read the description,
decided that it's exactly what I want, and ignored the warning.

Now I'm trying to inherit using a template. Instead of "destructor could
not be generated because a base class destructor is inaccessible", I now
have an error C2248 <name of base destructor> "cannot access private
member". Is this correct or a bug? I don't want the compiler to generate
a destructor for the base class, I won't declare any variables on the
stack and I will use the base Destroy function to deallocate it.

Template or no, in order to derive from a class, that class needs at least
one accessible constructor and an accessible destructor. It's an MS
extension (or bug, depending on your viewpoint) that the compiler let you
get away with it in your non-template case.

Can you simply make the base-class destructor protected instead of private?

-cd
 
V

Victor Bazarov

Ben said:
I have a POD type with a private destructor.

No such thing. PODs cannot not have private anything, PODs cannot have
user-defined destructors (8.5.1/1, 9/4).
There are a whole
hierarchy of derived POD types, all meant to be freed using a public
member function Destroy in the base class. I get warning C4624. I
read the description, decided that it's exactly what I want, and
ignored the warning.
Now I'm trying to inherit using a template. Instead of "destructor
could not be generated because a base class destructor is
inaccessible", I now have an error C2248 <name of base destructor>
"cannot access private member". Is this correct or a bug? I don't
want the compiler to generate a destructor for the base class, I
won't declare any variables on the stack and I will use the base
Destroy function to deallocate it. [...]

If the derived class does not have a private d-tor, the program will
try to provide one for you (whether you want it or not), which in turn
will try to call the base class d-tor, which you made private. So,
when deriving from a class with a private d-tor, declare your d-tor
private again.

V
 
T

Tamas Demjen

Ben said:
I have a POD type with a private destructor.

I'm sorry but it's not a POD. If you have a user defined destructor,
that's against the definition of the POD type.

If you derive from a non-POD class, and you don't supply a destructor,
the compiler will generate one for you. Just because you don't have an
explicit one, it doesn't mean you don't have one at all. The derived
destructor must be able to call the base, and if it's private, it's not
accessible. This essencially means that you can't derive from a class
that have a private destructor. This is my understanding.

Tom
 
B

Ben Voigt

Victor Bazarov said:
No such thing. PODs cannot not have private anything, PODs cannot have
user-defined destructors (8.5.1/1, 9/4).

Hmmm, think you're right about the destructor. However private helper
functions are certainly possible in a POD.

What do you call a class whose instances have no v-table, but isn't a POD?

If the derived class does not have a private d-tor, the program will
try to provide one for you (whether you want it or not), which in turn
will try to call the base class d-tor, which you made private. So,
when deriving from a class with a private d-tor, declare your d-tor
private again.

Tried that after posting and it works. Took them out again, and it works.
Slightly confused.
 
V

Victor Bazarov

Ben said:
Hmmm, think you're right about the destructor. However private helper
functions are certainly possible in a POD.

_By definition_ the presence of private or protected member makes the
class non-POD. There can be no discussion or argument about it.
What do you call a class whose instances have no v-table, but isn't a
POD?

A class. A UDT, if you need to use a TLA. And what does v-table have
to do with it?

V
 
B

Ben Voigt

Victor Bazarov said:
_By definition_ the presence of private or protected member makes the
class non-POD. There can be no discussion or argument about it.

A POD cannot have non-public variables. But it can have public member
functions, correct? Then naturally these can use private helpers
internally. Or no?

I thought a POD was anything that is a drop-in replacement for some C
struct. That means (1) layout compatible and (2) no reduced visibility for
any member. If any existing variable became hidden, it would break code
that worked on the struct. If any new variables were added, they would
break the layout. Therefore there can be no non-public variables. However
member functions and static members of any type do not affect the layout,
and do not break existing code referring to structure members, so they are
permitted, regardless of visibility.
A class. A UDT, if you need to use a TLA. And what does v-table have
to do with it?

A v-table is what makes an object. Without a v-table, there is no
polymorphism, no RTTI, in fact no awareness of 'type'. A class without a
v-table is just an assembly of variables and functions in a naming scope,
hardly any different from a namespace.
 
V

Victor Bazarov

Ben said:
A POD cannot have non-public variables. But it can have public member
functions, correct? Then naturally these can use private helpers
internally. Or no?

Are you not reading what I type here? Public member functions are OK
as long as they are not virtual. Nothing private and nothing protected.
_By definition_. If you want to challenge the definition, you should
go to 'comp.std.c++'. But I wouldn't recommend it. Learn the tools,
don't try to change them. If you need different tools, get different
tools, don't try to squeeze the existing tools into a different mold.
I thought a POD was anything that is a drop-in replacement for some C
struct. That means (1) layout compatible

Yes. C++ Standard says that the layout is pretty much known _between_
access specifiers. So, *across* access specifiers the layout is
somewhat a mystery (implementation-defined, yadda yadda).
and (2) no reduced
visibility for any member.

OK, so private and protected isn't that? Or are you trying to pull
some temporal characteristic here as well? There isn't any.
If any existing variable became hidden,
it would break code that worked on the struct.

Sigh... So, if you're writing _new_ code, it doesn't matter? What
kind of argument is that?
If any new variables
were added, they would break the layout. Therefore there can be no
non-public variables.

What if I add new public variables? Don't they break the layout of
an _existing_ struct?
However member functions and static members of
any type do not affect the layout,

Says who?
and do not break existing code
referring to structure members, so they are permitted, regardless of
visibility.

What existing code? What if I'm writing a new program altogether?
How the hell should the compiler know where the code comes from?
A v-table is what makes an object. Without a v-table, there is no
polymorphism, no RTTI, in fact no awareness of 'type'. A class
without a v-table is just an assembly of variables and functions in a
naming scope, hardly any different from a namespace.

Bull. An object is an area of computer memory, ones and zeros. There
are no RTTI, no 'type', no "awareness". Program is another set of
the same ones and zeros. See, anything can be taken to extreme and
made absurd, if one pleases. Object is a concept that exists in terms
of the program you write. Nothing more and nothing less. Same as
a class, a POD-struct, a function, a namespace, a variable, whatever.
Pull it out of its context and you can do whatever you want with it.

V
 
C

Carl Daniel [VC++ MVP]

Ben Voigt said:
A POD cannot have non-public variables. But it can have public member
functions, correct? Then naturally these can use private helpers
internally. Or no?

Not according to the C++ standard. It's generally acknowledged that the
standard's definition of POD is overly strict. There's work underway for
the next version of the C++ standard to relax the definition of POD to more
closely match actual practice (or alternatively, come up with a new name
that describes what people intuitively think of as POD).
I thought a POD was anything that is a drop-in replacement for some C
struct. That means (1) layout compatible and (2) no reduced visibility
for any member. If any existing variable became hidden, it would break
code that worked on the struct. If any new variables were added, they
would break the layout. Therefore there can be no non-public variables.
However member functions and static members of any type do not affect the
layout, and do not break existing code referring to structure members, so
they are permitted, regardless of visibility.

The restriction of no non-public member functions doesn't seem very useful,
but that's what the standard says.

-cd
 
T

Tom Widmer [VC++ MVP]

Carl said:
Not according to the C++ standard. It's generally acknowledged that the
standard's definition of POD is overly strict. There's work underway for
the next version of the C++ standard to relax the definition of POD to more
closely match actual practice (or alternatively, come up with a new name
that describes what people intuitively think of as POD).
The restriction of no non-public member functions doesn't seem very useful,
but that's what the standard says.

Are you and Victor sure? I can see no such restriction:

8.5.1/1
"An aggregate is an array or a class (clause 9) with no user-declared
constructors (12.1), no private or protected non-static data members
(clause 11), no base classes (clause 10), and no virtual functions (10.3)."

PODs add nothing further regarding member functions.

Tom
 
T

Tom Widmer [VC++ MVP]

Victor said:
_By definition_ the presence of private or protected member makes the
class non-POD. There can be no discussion or argument about it.

Citation please. I think private member functions (and private static
member variables) are allowed in PODs and aggregates.

Tom
 
T

Tom Widmer [VC++ MVP]

Ben said:
I have a POD type with a private destructor. There are a whole hierarchy of
derived POD types, all meant to be freed using a public member function
Destroy in the base class. I get warning C4624. I read the description,
decided that it's exactly what I want, and ignored the warning.

As said by others, your class becomes a non-POD as soon as you declare a
destructor. Additionally, derived classes are never POD types.
Now I'm trying to inherit using a template. Instead of "destructor could
not be generated because a base class destructor is inaccessible", I now
have an error C2248 <name of base destructor> "cannot access private
member". Is this correct or a bug?

It depends on whether your code is attempting to use the derived class
destructor (e.g. a call to delete will do that).

I don't want the compiler to generate a
destructor for the base class,

But you've written a destructor - it even does something (calls
FreeAgent();).

I won't declare any variables on the stack
and I will use the base Destroy function to deallocate it.

If you won't declare any variables on the stack, just drop your
declaration of a destructor - it isn't needed. Instead, to prevent
accidental external delete calls, you could declare a class operator new
public and operator delete protected, which shouldn't affect your POD
status. Instead, you could make the Destroy function call FreeAgent()
before delete this.
/**
** \brief Carries a request and any associated parameters.
**/
struct PNPEXPORT IConcurrentOperations::OpRequest abstract : OpMessage
{
...
private:
/**
** \brief Destructor, executes cleanup
**
** Calls FreeAgent to manage reference counting pAgent.
**
** Private visibility prevents declaration on the stack.
**/
~OpRequest()
{
FreeAgent();
}

public:
/**
** \brief Frees resources used by this request
**/
void Destroy( void )
{
delete this;

That is problematic, since your destructor isn't virtual. You can't
destroy an object through a base class pointer unless it has a virtual
destructor.
}
};

/**
** \param Base, should be derived from OpNotification or OpRequest
** and provide a default constructor.
**/
template<typename Base>
struct IConcurrentOperations::BufferedMessage : public Base
{...}

What are you trying to do? We might be able to suggest a workable design.

Tom
 
C

Carl Daniel [VC++ MVP]

Tom said:
Are you and Victor sure? I can see no such restriction:

8.5.1/1
"An aggregate is an array or a class (clause 9) with no user-declared
constructors (12.1), no private or protected non-static data members
(clause 11), no base classes (clause 10), and no virtual functions
(10.3)."
PODs add nothing further regarding member functions.

Well. now I'm going to have to look! At the time, I didn't have my copy of
the standard handy, Victor's stsatements rang true to me, and Victor is
rarely wrong about such things.

9/4 says:

"A POD-struct is an aggregate class that has no non-static data members of
type pointer to member, non-POD-struct, non-POD-union (or array of such
types) or reference, and has no user-defined copy assignment operator and no
user-defined destructor."

So the OP's class is not a POD because it has a user-defined destructor. My
statement above about no non-public member functions is incorrect - only
destructors and copy-assignment operators are mentioned in the definition of
POD (above and beyond aggregate) and there's no special consideration for
non-public function members at all.

-cd
 
B

Ben Voigt

What if I add new public variables? Don't they break the layout of
an _existing_ struct?

Still a POD, because it is layout compatible with some C struct, namely the
C struct that also has those public variables added.
Says who?

Says me. Non-virtual member functions and static members of any type add no
per-instance overhead, and occupy no space in the layout.
What existing code? What if I'm writing a new program altogether?

What does "Drop-in replacement" mean to you? A POD means you can
reinterpret_cast back and forth at will with the corresponding C struct.
You can create an instance of the POD, and pass it by reference to a C
function, and vice versa you can receive it from a C function, cast it as
the POD, and call POD member functions on it without losing type-safety.
You can also typedef the POD type in place of the old struct and not have
any visibility errors.
How the hell should the compiler know where the code comes from?

POD is not a compiler concept. The compiler only distinguishes between "has
a v-table" and "doesn't".
Bull. An object is an area of computer memory, ones and zeros. There
are no RTTI, no 'type', no "awareness". Program is another set of
the same ones and zeros. See, anything can be taken to extreme and
made absurd, if one pleases. Object is a concept that exists in terms
of the program you write. Nothing more and nothing less. Same as
a class, a POD-struct, a function, a namespace, a variable, whatever.
Pull it out of its context and you can do whatever you want with it.

An object class has a v-table uniquely identifying the type. Every instance
has a pointer to this v-table. Therefore the instance has an exact type,
known at runtime, for which that v-table is created. POD types have no
v-table.
 
C

Carl Daniel [VC++ MVP]

Ben Voigt said:
POD is not a compiler concept. The compiler only distinguishes between
"has a v-table" and "doesn't".

You're speaking pragmatically, and Victor is speaking theoretically. POD is
defined by the C++ standard to have a specific meaning, whether than meaning
has any concrete ramifications in the compiler or not. While it's true that
under VC++ only the presense of virtual functions or virtual base classes
affects object layout, there's nothing that requires a C++ compiler to work
that way.

What you call a POD is closer to what most programmers consider a "POD" - a
definition that's less restrictive than the one in the C++ standard.

-cd
 
B

Ben Voigt

Tom Widmer said:
As said by others, your class becomes a non-POD as soon as you declare a
destructor. Additionally, derived classes are never POD types.

Ok, I'm not really caring about being POD. I care about being able to use
and destroy it non-virtually.
It depends on whether your code is attempting to use the derived class
destructor (e.g. a call to delete will do that).

One of the derived classes had a gcroot member (to carry System::Exception
objects between threads). Not calling the destructor on that would be bad,
so now I'm explicitly setting it to nullptr before letting the base class
destroy it. What I will probably end up doing is formatting an error
message using Environment::StackTrace and passing that as raw UNICODE
characters.

I'm passing information between threads (one managed, one not) and if
something gets mixed up so there are still messages in flight (PostMessage)
when I call DestroyWindow, I'd like to not lose anything more than just
leaking a small buffer object (up to 200 bytes) on the heap. Since the .NET
gc can't track pointers inside message queues, this is how I've chosen to do
it.

Incidentally, this is why it's very important to me to avoid virtual calls
to anything. Anyone could drop messages into my queue with an arbitrary
LPARAM.

Toward that end, is it possible to filter WM_TIMER messages from being
passed to DispatchMessage in a .NET app?
I don't want the compiler to generate a

But you've written a destructor - it even does something (calls
FreeAgent();).

Sorry, I meant I didn't want the compiler to generate destructors for the
derived classes.
I won't declare any variables on the stack

If you won't declare any variables on the stack, just drop your
declaration of a destructor - it isn't needed. Instead, to prevent
accidental external delete calls, you could declare a class operator new
public and operator delete protected, which shouldn't affect your POD

Sadly, protected operator delete causes a compile error at every use of
operator new.
I think this is in case a constructor throws -- the instance isn't
constructed at that point, so the destructor needn't be accessible. But
operator delete needs to be. (/me frowns)
Actually that is it, because marking derived constructors nothrow with
throw() makes the error go away.
status. Instead, you could make the Destroy function call FreeAgent()
before delete this.

Ok, doing that. Removing destructor. I guess that makes declaration on the
stack possible again, which isn't really a problem although it's never
necessary.
That is problematic, since your destructor isn't virtual. You can't
destroy an object through a base class pointer unless it has a virtual
destructor.

If all derived types just add additional POD fields, then I wouldn't need to
destroy it virtually.
 
T

Tom Widmer [VC++ MVP]

Ben said:
POD is not a compiler concept. The compiler only distinguishes between "has
a v-table" and "doesn't".

Have you seen the intrinsic __is_pod(T) in VS2005?

Tom
 
T

Tom Widmer [VC++ MVP]

Ben said:
Ok, I'm not really caring about being POD. I care about being able to use
and destroy it non-virtually.

You can't do that portably even for POD types, unless you switch from
new/delete to malloc/free. More on that further down.
One of the derived classes had a gcroot member (to carry System::Exception
objects between threads). Not calling the destructor on that would be bad,
so now I'm explicitly setting it to nullptr before letting the base class
destroy it. What I will probably end up doing is formatting an error
message using Environment::StackTrace and passing that as raw UNICODE
characters.

I'm passing information between threads (one managed, one not) and if
something gets mixed up so there are still messages in flight (PostMessage)
when I call DestroyWindow, I'd like to not lose anything more than just
leaking a small buffer object (up to 200 bytes) on the heap. Since the .NET
gc can't track pointers inside message queues, this is how I've chosen to do
it.

That is in violation of the docs for PostMessage:
"If you send a message in the range below WM_USER to the asynchronous
message functions (PostMessage, SendNotifyMessage, and
SendMessageCallback), its message parameters cannot include pointers.
Otherwise, the operation will fail. The functions will return before the
receiving thread has had a chance to process the message and the sender
will free the memory before it is used."

In other words, you shouldn't fire off pointers to a window and expect
the window to delete them. Instead, you should use SendMessage, and
delete them yourself. This then avoids the whole issue.
Incidentally, this is why it's very important to me to avoid virtual calls
to anything. Anyone could drop messages into my queue with an arbitrary
LPARAM.

I don't understand that.
Toward that end, is it possible to filter WM_TIMER messages from being
passed to DispatchMessage in a .NET app?

Sorry, I've no .NET expertise.
Sorry, I meant I didn't want the compiler to generate destructors for the
derived classes.

Ahh, ok.
Sadly, protected operator delete causes a compile error at every use of
operator new.
I think this is in case a constructor throws -- the instance isn't
constructed at that point, so the destructor needn't be accessible. But
operator delete needs to be. (/me frowns)
Actually that is it, because marking derived constructors nothrow with
throw() makes the error go away.

Ahh, yes. I didn't realise the derived classes have destructors (which
is yet another violation of the requirements on POD data).
If all derived types just add additional POD fields, then I wouldn't need to
destroy it virtually.

Calling delete with the wrong type is illegal C++, unless the destructor
is virtual. It happens to work on some compilers and versions, but not
necessarily all, since the compiler is at liberty to use the type of the
deleted object to determine the size of the allocation that created it.
Also, a debugging implementation might check that constructed objects
have their destructors run.

Based on what you've said, the easiest option would be to stop using
PostMessage and instead destroy messages at the sending site. If you
can't do that, you are probably best off moving to using real POD
objects, dropping your use of new and delete expressions, and using
::blush:perator new and ::blush:perator delete (or malloc and free), which work
fine with raw memory, and don't care about pointer types or destructors.
If you want more standards compliant code, you could replace
constructors with initialization functions, and drop inheritence
entirely (making your Destroy function a free function).

It seems to me that you're conflating OO and C style programming in an
unnecessary and confusing way.

Tom
 
A

Alex Blekhman

Tom Widmer said:
That is in violation of the docs for PostMessage:
"If you send a message in the range below WM_USER to the
asynchronous message functions (PostMessage,
SendNotifyMessage, and SendMessageCallback), its message
parameters cannot include pointers. Otherwise, the
operation will fail. The functions will return before the
receiving thread has had a chance to process the message
and the sender will free the memory before it is used."

In other words, you shouldn't fire off pointers to a
window and expect the window to delete them. Instead, you
should use SendMessage, and delete them yourself. This
then avoids the whole issue.


I think you're interpreting this paragraph in a too strict
way. It says that if you want pointer marshalling to work
(for messages < WM_USER), then don't use asynchronous
message functions. You still can use pointers as message
parameters for messages above WM_USER. Just don't expect any
free marshalling services from system. As long as you post
pointers within the same process and free them at the right
moment there is no problem with PostMessage.


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top