为什么 (i|o)fstream 为文件名采用 const char* 参数?

Why does (i|o)fstream take a const char* parameter for a file name?(为什么 (i|o)fstream 为文件名采用 const char* 参数?)

本文介绍了为什么 (i|o)fstream 为文件名采用 const char* 参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么std::(i|o)fstream类的构造函数和open方法以const char*<的形式将文件名作为参数/code> 而不是 std::string?似乎 STL 的创建者希望使用他们编写的内容,而不是使用他们编写的类来替换的类型.

Why does the constructor and open method of the std::(i|o)fstream classes take the name of a file as a parameter in the form of a const char* instead of an std::string? It seems like the creators of the STL would want to use what they had written instead of using the type they wrote a class to replace.

推荐答案

Class std::string 实现了运行时大小可调整的字符串"的概念.这是应该使用这个类的时候——当你需要一个字符串,它的大小只在运行时知道,并且在运行时也可以调整大小.在您不需要这些功能的情况下,使用 std::string 是一种矫枉过正.显然,该库的作者并不认为他们需要一个运行时可调整大小的字符串来表示文件名,所以他们选择了一个简约的解决方案:他们使用了一个 C 字符串,其中一个 C 字符串就足够了.这实际上是设计库接口的一个很好的原则:永远不要需要你并不真正需要的东西.

Class std::string implements the concept of "run-time-sized resizable string". This is when this class should be used - when you need a string whose size is only known at run-time and which is run-time resizable as well. In situations when you don't need these features using std::string is an overkill. Apparently, the authors of the library didn't think that they needed a run-time resizable string to represent a file name, so they opted for a minimalistic solution: they used a C-string where a C-string was sufficient. This is actually a very good principle for designing library interfaces: never require something that you don't really need.

确实,现在我们经常看到有人鼓励 C++ 程序员在需要字符串时使用 std::string.他们经常声称经典的 C 字符串应该保留给 C 代码.在一般情况下,这是一种虚假的哲学.无偿使用像 std::string 这样相对较重的对象在 Java 等语言中更合适,但在 C++ 中通常是不可接受的.

It is true that these days we often see people who encourage C++ programmers to use std::string whenever they need a string, any string. They often claim that classic C strings should be reserved to C code. In general case this is a bogus philosophy. Gratuitous use of comparatively heavy objects like std::string is more appropriate in languages like Java, but is normally unacceptable in C++.

是的,在某些 C++ 应用程序中始终使用 std::string 是可能的(可以用 C++ 编写 Java 程序"),但在这样的情况下作为 C++ 标准库的通用低级库迫使用户在没有充分理由(即强加不必要的要求)的情况下使用 std::string 看起来不太好.

Yes, it is possible to get away with using std::string all the time in some C++ applications ("it is possible to write a Java program in C++"), but in such a generic low-level library as C++ standard library forcing the user to use std::string without a good reason (i.e. imposing unnecessary requirements) would not look good.

这篇关于为什么 (i|o)fstream 为文件名采用 const char* 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为什么 (i|o)fstream 为文件名采用 const char* 参数?

基础教程推荐