problem in C++ pointer

James Stern jsternitg@yahoo.com
Thu Mar 16 08:39:00 GMT 2000


--- Jay Krell <jay.krell@cornell.edu> wrote:

> [... Is this undefined?]
> class X
> {
> public:
>     X* F(int i) { printf("%d", i); return this;}
> };
> 
> int i = 0;
> X x, *px = &x;
> px->F(i++)->F(i++)->F(i++);
> 
> is the expected output 012 or is it undefined?

Undefined.  The C++ Standard requires a sequence point before the
function is called but not before its argument are evaluated.  And
the "->" operators don't impose an evaluation order on their operands
either.

This has some interesting consequences.  Consider:

   cout << 'a' << flush;

The obvious implementation would be to make "flush" an object whose
constructor flushes the stream (although you'd have to pass the stream
as an argument then).

But that won't work because there's nothing to stop the implementation
from constructing "flush" before calling either operator<<.

So the iostream package uses a different solution.  It makes "flush" a
function pointer.  By itself, "flush" does nothing.  But an overloaded
operator<< accepts "flush" as an argument and *it* flushes the stream.

All this is necessary because the order of evaluation of operands above
is unspecified.  (Except that all operands will be evaluated before the
function is called.)  All that's really guaranteed is that the
operator<< calls will be evaluated left-to-right.

> [...] 
> [intro.execution]1.8.17 "..There is also a sequence point after the
> copying
> of a returned value and before the execution of any expressions
> outside the
> function". I don't know if that "copying of a returned value" applies
> to
> pointers and references, and I find "expressions outside the
> function"
> unclear.
> 
> Ordinarily, the sides of a -> I don't believe have a defined order of
> evaluation:

True.

> [...] 

> 
> "sequence point" is not in the index..

It is in my copy.  Maybe you're looking at a draft?  "point" is a
subtopic under "sequence."

=====
-- 
Opinions expressed above are not necessarily my employer's.
James M. Stern
ITG Inc.  Culver City, CA (213) 270-7955

__________________________________________________
Do You Yahoo!?
Talk to your friends online with Yahoo! Messenger.
http://im.yahoo.com

--
Want to unsubscribe from this list?
Send a message to cygwin-unsubscribe@sourceware.cygnus.com



More information about the Cygwin mailing list