Re: smart pointer / constructor design problem
On Apr 17, 4:12 pm, Andrew Tomazos <and...@tomazos.com> wrote:
[snip]
void f(Handle<C> c)
{
...
}
class C : public Handleable
{
C()
{
f(this);
}
}
Handle<C> c = new C(); // crash, f's Handle<C> parameter causes
destruction of C instance before c's constructor can increment ref
count.
I'm trying to think of a nice way around this.
How about documenting this problem and leaving it up to the
programmer to do his job? I think this problem should not be
solved. Why? What they're doing is undefined behavior and
likely to crash anyway. Since the object lifetime doesn't begin
until the constructor successfully completes, if they pass the
partially constructed object to another function, they're passing
GARBAGE.
If your users write code with undefined behavior as your code
demonstrates, there is nothing you can do to recover for them.
The best thing for your user is to detect this severe flaw in
their code, and your opportunity to help is realized by crashing.
If you don't allow this crash, user code might continue to
run (for a while) in a corrupted state, making debugging much,
much harder once the bug's symptoms start showing up.
IMHO, early detection is better than late, so don't "fix" this,
as doing so only facilitates your users to write faulty,
harder-to-debug code.
Chris
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]