Re: Verify and expression
alfps@start.no (Alf P. Steinbach) wrote (abridged):
but this evaluates the condition twice, which is unacceptable if it
has side effects.
Well, as I mentioned (and exemplified) elsethread, that's easy to fix
technically,
If I understand what you are referring to, you fixed it by throwing away
the type and value of the expression, and simply returned true if it
succeeded. Which is reasonable because it was what the original poster's
code did in debug builds. I, on the other hand, was influenced by
Frederick Gotham's code, which used a template to preserve the type and
value. I think it would be OK to return 0 or false on failure, but if it
preserved the value on success it could be used like:
char *s = VERIFY( strdup( "test" ), "out of memory" );
which would be more useful.
(You mention also using a global variable to store the condition's value,
but I think that suffers from not being re-entrant or thread-safe. If you
had something else in mind, I missed it.)
but as I also mentioned there, the better solution IMO is
to require the condition to not have side effects.
The original poster wanted a replacement (or upgrade) for the MFC VERIFY.
The whole point of the MFC version is that it allows side effects in the
condition - otherwise you would just use ASSERT. (The MFC version does not
return the result, so if the expression has no side effects and no result
there's no need to include it in release builds.) So I see allowing side
effects in the condition as crucial part of the specification.
However, personally I think it would be OK to forbid side effects in the
report argument.
#define VERIFY( condition, report ) \
verify( (condition), (VerifyArgs() << report),\
__FILE__, __LINE__ )
where VerifyArgs is a class with template members which capture the types
and values of report, and verify itself is a template function which
returns the type and value of condition. I would expect the report
argument to be just a list of strings values and values:
int c = VERIFY( a+b, "a=" << a << " b=" << b );
so it shouldn't need side effects - provided, of course, the values aren't
displayed or logged or whatever if the check succeeds. I expect the author
of ModAssert would disagree with me.
Repeat above comment, + that this is an example of invalid code, but
what's the point of that?
I posted the invalid code to illustrate the problem: to show the kind of
thing we need to do, but can't.
-- Dave Harris, Nottingham, UK.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]