简体   繁体   English

cout/cin 是否在内部调用 printf() / scanf() 就像 `new` 调用 malloc?

[英]Does cout/cin internally call printf() / scanf() like `new` calls malloc?

I have looked it up over the Internet.我已经通过互联网查找了它。 I have found many answers comparing cin vs scanf() and cout vs printf() , but never found if cin actually uses scanf() internally like new operator in C++ uses malloc() function of C.我发现了很多比较cinscanf()coutprintf()的答案,但从未发现cin是否实际上在内部使用scanf()就像 C++ 中的new运算符使用malloc() function 的 Z0D617F8370CAD1D4DE112F

The C++ standard does not specify how standard library facilities such as std::cin and std::cout are implemented, only how they should behave. C++ 标准没有指定标准库设施如std::cinstd::cout是如何实现的,只指定它们的行为方式。 Whether the C++ I/O functions call their C counterparts is up to the implementation. C++ I/O 函数是否调用其 C 对应函数取决于实现。

As an example of how the C++ I/O streams can be implemented, we can look at the source code of libstdc++, which is GCC's standard library implementation.作为如何实现 C++ I/O 流的示例,我们可以查看 libstdc++ 的源代码,它是 GCC 的标准库实现。 The std::basic_istream& operator>>(int&) function which is the one called when you use std::cin >> x to read an int calls some functions which call other functions and it eventually reaches this _M_extract_int function that actually parses the integer. The std::basic_istream& operator>>(int&) function which is the one called when you use std::cin >> x to read an int calls some functions which call other functions and it eventually reaches this _M_extract_int function that actually parses the integer . Therefore, libstdc++ does not implement the stream extraction operator for ints using C I/O functions.因此,libstdc++ 没有为使用 C I/O 函数的整数实现 stream 提取运算符。 Still, remember that this is only one example and other standard library implementations may be different.不过,请记住,这只是一个示例,其他标准库实现可能会有所不同。

C++ standard specifies what objects std::cout and std::cin must do. C++ 标准规定了对象std::coutstd::cin必须做什么。 How it is implemented depends on vendor.如何实现取决于供应商。

The best way to be sure is to read the source code of given implementation.最好的方法是阅读给定实现的源代码。

You also need to know, that under the hood printf() uses also other functions.您还需要知道,在后台printf()还使用其他功能。 It would be optimization wise to implement cout with them, as this object doesn't work exactly as printf() function.用它们实现cout是明智的,因为这个 object 与printf() function 的工作方式不同。

There is also a little to no chance of std::cin using scanf() , as it tends to be problematic (read more onA beginners' guide away from scanf() ).使用scanf()std::cin也几乎没有机会,因为它往往会出现问题(阅读更多关于远离scanf()的初学者指南)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM