Re: Order of evaluation of expression
Paul 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?
If your idea is to make sure that 'Latch' is constructed before the two
string literals are *output*, then you're OK. However, do not rely on
your 'Latch' to be constructed when some other subexpressions need to be
evaluated and they are functions to be called, similar to
std::wcout << Latch(lck) << getSomething1() << getSomething2();
since the order of evaluation of 'Latch' constructor, and the other two
functions ('getXXX') is *unspecified*, and can be different even in *two
consecutive statements*. IOW, when 'getSomething1' or 'getSomething2'
are called, the 'Latch' may not be constructed yet.
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.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask