Re: ctor requires operator delete when using C++ exception handling
vl106 ha scritto:
Hi,
It seems that C++ exception handling (we currently don't use it
really)
requires class to have operator delete available.
<snip>
Therefore I declared but did not implement operator delete. Now
clients
cannot call delete any more and they cannot delete the objects. They
will receive a linker error.
But this only works when exception handling is turned off. When turned
on I
(too) get the linker error:
unresolved external symbol "public: static void __cdecl C::operator
delete(void *)"
(??3C@@SAXPAX@Z) referenced in function
__unwindfunclet$?create_C@Service@@QAE?AVC_ptr@@XZ$0
First, it's good to understand why operator delete is needed. In fact
it's not really needed by C::C(), it's needed by the evaluation of the
new-expression, that is:
C* p = new C;
If, after the memory has been allocated, the initialization of the newly
created object fails with an exception, then the program shall attempt
to release the allocated memory before re-throwing the exception. This
is done by calling C::operator delete, that you declared.
Therefore, one workaround that avoid spurious friend declaration might
be the following:
1) declare both operator new and operator delete as private:
private:
void* operator new(size_t n) { return ::operator new(n); }
void operator delete(void* p) { ::operator delete(p); }
(defining operator new is not strictly necessary, but it's bad style to
define one without the other)
2) declare a static factory method:
public:
static C* create_C(/* param here */) { return new C(/**/); }
That's it. You might still need some friendship in order to delete C
instances, but as there was no deletion code in your snippet, I can't
help your there.
In this framework, I would also declare all constructors as private, but
that's up to you.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]