cout的缓冲如何工作?

luc*_*cas 0 c++ buffer cout

我知道cout几天前有缓冲区,当我google它时,据说缓冲区有点像堆栈并从右到左获取cout和printf的输出,然后将它们输出(到控制台或文件) )从顶部到bottem.像这样,

a = 1; b = 2; c = 3;
cout<<a<<b<<c<<endl;
buffer?|3|2|1|<-   (take “<-” as a poniter)

output?|3|2|<-     (output 1)
        |3|<-       (output 2)
        |<-         (output 3)
Run Code Online (Sandbox Code Playgroud)

然后我写下面的代码,

#include <iostream> 
using namespace std; 
int c = 6;
int f() 
{   
    c+=1; 
    return c; 
} 

int main() 
{ 
     int i = 0; 
     cout <<"i="<<i<<" i++="<<i++<<" i--="<<i--<<endl; 
     i = 0;
     printf("i=%d i++=%d i--=%d\n" , i , i++ ,i-- );

     cout<<f()<<" "<<f()<<" "<<f()<<endl; 
     c = 6;
     printf("%d %d %d\n" , f() , f() ,f() );
     system("pause");
     return 0; 
}
Run Code Online (Sandbox Code Playgroud)

在VS2005下,输出为

i=0 i++=-1 i--=0
i=0 i++=-1 i--=0
9 8 7
9 8 7
Run Code Online (Sandbox Code Playgroud)

似乎堆栈的方式是正确的〜但是,我昨天读了C++ Primer Plus,据说cout从左到右工作,每次返回一个对象(cout),所以"这是让你连接输出的功能通过使用插入".但从左到右的方式无法解释cout <

然后Alnitak告诉我,"<<运算符实际上是ostream&operator <<(ostream&os,int),所以写另一种方法是:operator <<(operator <<(operator <<(cout,a),b ), C )",

如果首先评估最正确的参数,可以解释一下.

现在我对cout缓冲区如何工作感到困惑,有人可以帮助我吗?

dir*_*tly 11

你混合了很多东西.至今:

  • 实施细节 cout
  • 链式电话
  • 召集会议

尝试分别阅读它们.并且不要一气呵成地考虑所有这些.

printf("i =%d i ++ =%d i - =%d \n",i,i ++,i--);

上面的行调用了未定义的行为.阅读FAQ 3.2.注意,您观察到的是函数调用约定的副作用以及特定实现(即您的)在堆栈中传递参数的方式.如果您在其他机器上工作,则不保证这一点.

我认为你将函数调用的顺序与缓冲混淆.当您有一个cout语句后跟多个插入时,<<您实际上是一个接一个地调用多个函数调用.所以,如果你要写:

cout << 42 << 0;
Run Code Online (Sandbox Code Playgroud)

这真的意味着:你打电话,

cout = operator<<(cout, 42)
Run Code Online (Sandbox Code Playgroud)

然后在另一个调用中使用return返回到同一个运算符:

cout = operator<<(cout, 0)
Run Code Online (Sandbox Code Playgroud)

您通过上述测试的内容不会告诉您任何cout内部表示.我建议你看看头文件了解更多.