前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​SL.io.3:优先使用iostream进行I / O

C++核心准则​SL.io.3:优先使用iostream进行I / O

作者头像
面向对象思考
发布2020-10-30 11:34:13
8490
发布2020-10-30 11:34:13
举报

SL.io.3: Prefer iostreams for I/O

SL.io.3:优先使用iostream进行I / O

Reason(原因)

iostreams are safe, flexible, and extensible.

iostream安全,灵活且可扩展。

Example(示例)

// write a complex number:
complex<double> z{ 3, 4 };
cout << z << '\n';

complex is a user-defined type and its I/O is defined without modifying the iostream library.

complex是用户定义的类型,无需修改iostream库即可定义其I / O。

Example(示例)

// read a file of complex numbers:
for (complex<double> z; cin >> z; )
    v.push_back(z);
Exception(例外)

??? performance ???

??? 性能???

Discussion: iostreams vs. the printf() family

讨论:iostreams与printf()函数群

It is often (and often correctly) pointed out that the printf() family has two advantages compared to iostreams: flexibility of formatting and performance. This has to be weighed against iostreams advantages of extensibility to handle user-defined types, resilient against security violations, implicit memory management, and locale handling.

人们经常(经常正确地)指出,与iostream相比,printf()函数群具有两个优点:格式化的灵活性和性能。必须权衡iostream的优势:处理用户定义的类型时的可扩展性,可抵御安全性违规,隐式内存管理和区域设置处理。

If you need I/O performance, you can almost always do better than printf().

如果需要保证I / O性能,iostream几乎可以总是比printf()更好。

gets(), scanf() using %s, and printf() using %s are security hazards (vulnerable to buffer overflow and generally error-prone). C11 defines some "optional extensions" that do extra checking of their arguments. If present in your C library, gets_s(), scanf_s(), and printf_s() might be safer alternatives, but they are still not type safe.

使用%s的gets(),scanf()和使用%s的printf()都有安全隐患(很容易造成缓冲区溢出并且通常容易出错)。C11定义了一些“可选扩展”,对它们的参数进行了额外的检查。如果是在使用C语言库,gets_s(),scanf_s()和printf_s()可能是更安全的选项,但它们仍然不是类型安全的。

Enforcement(实施建议)

Optionally flag <cstdio> and <stdio.h>.

(可选)标记<cstdio>和<stdio.h>。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slio3-prefer-iostreams-for-io

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-10-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SL.io.3: Prefer iostreams for I/O
    • Exception(例外)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档