Re: Order of evaluation of expression
On Tue, 3 Jun 2008 08:51:01 -0700, Paul <vhr@newsgroups.nospam> wrote:
I am thinking of implementing a manipulator for a stream whose role would be
to lock the stream, run some prefix code (output a few initial values) and
then run some suffix code (flush and unlock the stream).
The code below illustrates locking.
struct Lock {
void lock();
void unlock();
};
struct Latch {
Latch(Lock& lck) : lock(lck) { lock.lock(); }
~Latch() { lock.unlock(); }
private:
Lock& lock;
};
inline std::wostream& operator <<(std::wostream& os, const Latch&)
{
return os;
}
int main()
{
Lock lck;
std::wcout << Latch(lck) << L"Something else 1.\n" << L"Something else
2.\n";
return 0;
}
The code seems to be working all right. Is there nothing wrong with this idea?
My way of thinking is this. The arguments for the call to the << operator
will be created before the call. The order of creation is unspecified but
this does not matter - it is the output itself that does. My initial concerns
were to do with the order of evaluation of an expression: whether, say, it
can happen that evaluation will proceed from the end and not just with the
argument creation but with actual outputting (with the ultimate result
obviously being equivalent to proceeding from the beginning). The << operator
returns a reference, though, so that output builds on the result of previous
returns from the call, so it is difficult to see what can go wrong.
Call operator<< f and put it in functional notation:
f(f(f(wcout, Latch), "1"), "2");
Certainly, Latch will have been evaluated before the inner "f" is entered,
and the "output" of Latch will have completed before the output of "1"
begins, because the result of the former's "f" is required to call the
latter's "f". The necessary sequence points are all there (function
entry/exit), the Latch object lives on 'til the end of the full-expression
(the whole statement), and so this is OK. As you noted, it would be a
problem if you were expecting Latch to be evaluated before "1" and "2",
because that is not guaranteed; I went into a lot of detail on that in this
post:
http://groups.google.com/group/microsoft.public.vc.language/msg/a5d3b3f8a4e3797c
Assuming we're talking about a mutex, it's more usual to name your classes
Mutex and Lock instead of Lock and Latch, and your Mutex object would be
global or otherwise available to other threads. Instead of playing these
manipulator games, I would just write:
Lock lk(mx);
std::wcout << L"Something else 1.\n" << L"Something else 2.\n";
If you need finer control of the lifetime of lk, you can use:
// BLOCK
{
Lock lk(mx);
std::wcout << L"Something else 1.\n" << L"Something else 2.\n";
}
I think it's clearer this way. It's what you have to do with just about all
other classes.
--
Doug Harrison
Visual C++ MVP