c++ - 为什么 std::fstream 类不采用 std::string?

这不是一个设计问题,真的,虽然看起来很像。 (嗯,好吧,这是一个设计问题)。我想知道为什么 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::strings 与 fstreams 一起使用。还假设 C 字符串可以转换为 std::strings,就像当前标准中的状态一样。现在,考虑以下几点:

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/

相关文章:

c++ - 我收到错误 "invalid use of incomplete type ' 类映射'

c++ - 计算机如何进行浮点运算?

c++ - std::pair 的顺序是否明确?

c++ - 如何在编译时检查结构的大小?

c++ - VS2012 在 64 位目标中 vector 的性能不佳

c++ - 如何强制 gcc 链接未使用的静态库

c++ - C 和 C++ 中的 1LL 或 2LL 是什么?

c++ - 如何让我的类(class)成为 google-test 类(class)的 friend

c++ - std::map 如何提供常量 size() 操作?

c++ - 访问另一个子类中基类的 protected 成员