这不是一个设计问题,真的,虽然看起来很像。 (嗯,好吧,这是一个设计问题)。我想知道为什么 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
吗?
最佳答案
通过采用 C 字符串 C++03 std::fstream
类减少了对 std::string
类的依赖。然而,在 C++11 中,std::fstream
类确实允许为其构造函数参数传递 std::string
。
现在,您可能想知道为什么没有从 std:string
到 C 字符串的透明转换,所以需要 C 字符串的类仍然可以采用 std: :string
就像一个期望 std::string
的类可以接受一个 C 字符串。
原因是这会导致转换周期,进而可能导致问题。例如,假设 std::string
可以转换为 C 字符串,这样您就可以将 std::string
s 与 fstream
s 一起使用。还假设 C 字符串可以转换为 std::string
s,就像当前标准中的状态一样。现在,考虑以下几点:
void f(std::string str1, std::string str2);
void f(char* cstr1, char* cstr2);
void g()
{
char* cstr = "abc";
std::string str = "def";
f(cstr, str); // ERROR: ambiguous
}
因为您可以在 std::string
和 C 字符串之间转换任何一种方式,所以对 f()
的调用可以解析为两个 f 中的任何一个()
替代品,因此是模棱两可的。解决方案是通过明确一个转换方向来打破转换周期,这就是 STL 选择使用 c_str()
所做的事情。
https://stackoverflow.com/questions/32332/