"Travis Spencer" <tr************@hotmail.com> wrote in message
news:bi*********@enews2.newsguy.com...
Hello,
I am trying to expose a C++ class to C clients using a C-compatible
wrapper API. While doing so, I hit a little snag. When a C client deletes one on
my classes using the provided delete method, shouldn't the pointer that
passed to DeleteFoo be null when returned?
No because C and C++ use call by value. A function can never change its
parameters in a way that is visible to the caller under any circumstances.
This is because the function takes a copy of the parameters passed to it,
even if the function changes a parameter, its only a copy of the one that
was supplied by the caller.
Consider
int func(int x)
{
x = 2;
}
int main()
{
int y = 1;
func(y);
cout << y; // outputs 1
}
This is basic C and C++. Your example involves pointers, my examples uses
integers, but there is no difference. Using pointers you can changes what is
pointed to, but that's a completely different situation.
The C++ exception is when references are involved, then a reference to the
oiginal parameter is taken, not a copy, so the function can change the
original parameter.
I don't think there is much point in doing what you are trying to do.
Consider
void DeleteFoo(FOO_HANDLE f);
class Foo { /* Compiler generated ctor and dtor */ };
int main(int argc, char** argv)
{
// Foos are normally created by C clients using my CreateFoo API
// function, but this is just a demo.
FOO_HANDLE f = new Foo;
FOO_HANDLE annoying_copy = f;
DeleteFoo(f);
if (annoying_copy != NULL)
std::cerr << "copy != NULL. Darn!" << std::endl;
else
std::cout << "copy == NULL. Cool!" << std::endl;
}
even if you did make f NULL, there is no way you can touch annoying_copy.
Assuming that your client is going to do things like call functions with
FOO_HANDLE or put FOO_HANDLE into data structures there are always going to
be copies the original FOO_HANDLE.
The only way to do this cleanly is to make FOO_HANDLE a class which has a
destructor. Then the destructor can sort itself out. Since you are
programming for C clients this is not possible, but C programmers have this
sort of headache all the time so they aren't going to mind.
john