当串联调用 obj.F1().F2().F3( sin(x) ) 时,何时计算参数?
我使用流运算符(例如operator<<(const char*)
)进行日志记录。在我的单元测试中,我有一个如下所示的测试:
MyLogger oLogger;
oLogger << "charly";
oLogger << "foo" << sleep( 10 ) << "bar";
oLogger << "marcus";
首先我执行了第二个线程,它应该同时记录。我想知道,为什么在 "foo"
和 "bar"
之间没有生成其他日志输出。所以我在每个操作员中打印了当前时间。我期待这样的事情:
50 sec 137051 usec charly
50 sec 137930 usec foo
60 sec 138014 usec 0
60 sec 138047 usec bar
60 sec 138088 usec marcus
但是得到了这个:
50 sec 137051 usec charly
60 sec 137930 usec foo
60 sec 138014 usec 0
60 sec 138047 usec bar
60 sec 138088 usec marcus
以下想法有什么问题:
[ 0 sec] MyLogger& MyLogger::operator<<( "charly" ) is processed.
[ 0 sec] MyLogger& MyLogger::operator<<( "foo" ) is processed.
The return value is used for the next function.
[ 0 sec] int sleep( 10 ) is processed - this takes 10 seconds until the return
value is available
[10 sec] MyLogger& MyLogger::operator<<( 0 ) is processed
( "0" is the return value of sleep(10) )
[10 sec] MyLogger& MyLogger::operator<<( "bar" ) is processed
但是出于什么原因, MyLogger::operator<<( "foo" )
在 之后处理睡眠(10)?
I use the streaming operators (e.g. operator<<(const char*)
) for logging. In my unit tests I have a test like the following:
MyLogger oLogger;
oLogger << "charly";
oLogger << "foo" << sleep( 10 ) << "bar";
oLogger << "marcus";
First I executed a second thread, which should log at the same time. I was wondering, why between "foo"
and "bar"
no other log-output was generated. So I printed in each operator the current time . I expected something like this:
50 sec 137051 usec charly
50 sec 137930 usec foo
60 sec 138014 usec 0
60 sec 138047 usec bar
60 sec 138088 usec marcus
but got this:
50 sec 137051 usec charly
60 sec 137930 usec foo
60 sec 138014 usec 0
60 sec 138047 usec bar
60 sec 138088 usec marcus
What is wrong with the following idea:
[ 0 sec] MyLogger& MyLogger::operator<<( "charly" ) is processed.
[ 0 sec] MyLogger& MyLogger::operator<<( "foo" ) is processed.
The return value is used for the next function.
[ 0 sec] int sleep( 10 ) is processed - this takes 10 seconds until the return
value is available
[10 sec] MyLogger& MyLogger::operator<<( 0 ) is processed
( "0" is the return value of sleep(10) )
[10 sec] MyLogger& MyLogger::operator<<( "bar" ) is processed
But for what reason ever, the MyLogger::operator<<( "foo" )
is processed after sleep(10)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是可接受的行为,因为没有指定“operator<<”操作数的顺序。正在被评估,并且 TTBOMK gcc 通常以相反的顺序执行此操作,以便以正确的顺序将参数放入堆栈以供下一个函数调用。
从堆栈机的角度来思考:
This is acceptable behaviour, as it is not specified in which order operands to "operator<<" are being evaluated, and TTBOMK gcc often does it in reverse order to get the parameters onto the stack in the right order for the next function call.
Think of it in terms of a stack machine: