C++ output stream floating point call chain [closed]

泪湿孤枕 提交于 2019-12-12 20:13:06

问题


In C++, when I do

std::cout << 1.2;

what is the actual chain of functions that are called to actually display the number? I realize this is compiler specific, but I am interested in particular with the Gnu libstdc++ implementation.

In C, calling printf delegates to vfprintf, which through jump tables calls __printf_fp in glibc. I'm looking for an analogous chain in the pure C++ setting.


回答1:


Clearly, it will call ostream::operator<< first but it may be library specific beyond that. The best way to answer this is to debug into the code and follow the functions as they occur. This will not only tell you what functions are called but tell your about edge cases and error handling that occurs. Looking at the code may help but it is likely convoluted.

Using this code:

std::cout << 1.2f;

... here is what is does in Visual Studio 2012 without the noise:

  1. operator<<(float _Val) (std::basic_ostream<_Elem, _Traits>)
    1. Initialize a state variable to good.
    2. Call use_facet<_Facet>(const locale & _Loc) (std) to get the num_put facet.
    3. Call num_put(_OutIt _Dest, ios_base& _Iosbase, _Elem _Fill, double _Val) (std) to write the float to the output stream (converted to a double) using local specific formatting. Internally, this:
      1. Checks the precision, such fixed, to see if the default formatting has been modified.
      2. Formats the number and writes it to the output as characters to the current iterator used by the stream.
    4. Set the state variable to bad if the operation failed.
    5. Call setstate to the state.

So most of the work is actually done in the num_put facet, which writes to an iterator for the output stream.



来源:https://stackoverflow.com/questions/12699876/c-output-stream-floating-point-call-chain

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!