这并不是一个设计问题,尽管它可能看起来像是。 (好吧,好吧,这有点像一个设计问题)。 我想知道的是为什么C ++ std :: fstream
类在其构造函数或打开方法中不使用std :: string
。 每个人都喜欢代码示例,所以:
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string filename = "testfile";
std::ifstream fin;
fin.open(filename.c_str()); // Works just fine.
fin.close();
//fin.open(filename); // Error: no such method.
//fin.close();
}
在处理文件时,这种情况总是让我感到困扰。C++ 库肯定会尽可能使用 std::string
,不是吗?
f(char*,std::string)
是一个精确匹配,而其他的则需要转换,因此第一个函数将是最佳可行函数。如果您删除了第一个f
,那么由于"(char*&,std::string&) -> (char*,std::string) -> (char*,char*)"是一个更好的转换序列,而不是"(char*&,std::string&) -> (char*,std::string) -> (std::string,char*)",第二个f
将成为最佳可行函数。我有什么遗漏吗? - outisGMP
依赖于shorts),而且(2)char*
是有害的,如果用户没有必要使用它,你不应该鼓励他们使用它,编译时间中的毫秒值完全值得,最后(3)他们本可以定义<stringfwd>
并在不依赖它的情况下使用字符串,所以我认为,在这种情况下,解耦依赖关系根本不是一个有效的理由。 - Elazar Leibovichc_str()
进行显式转换而不是使用转换构造函数进行隐式类型转换的原因是,C字符串需要额外的\0
,因此std::string
无法返回指向其内部表示的const char*
指针,这将导致性能下降。使用显式转换,程序员可以更好地决定。 - Micha Wiedenmann