3

为什么下面的代码能编译进去C++11而不能编译进去C++03gcccl

#include <string>
#include <iostream>
#include <fstream>

int main(int argc, char* argv[]) {
    const std::string t("Hello");
    std::ofstream out(t);
}

为什么C++03流不接受std::string作为构造函数参数?这个决定是基于某事还是偶然发生的?

4

3 回答 3

9

当使用严格符合 C++03 的编译器编译代码时,代码会失败,因为采用 a 的构造函数std::string仅在 C++11 中添加。

至于“是不是基于一些聪明的东西”这个问题,随着接口增加,可以推断没有技术原因将其省略。

这是一个额外的便利,因为如果你有一个std::string,你总是可以调用.c_str()来获取一个适合与旧接口一起使用的 C 字符串。(正如 C++11 中的文档所说,采用的构造函数与调用相应的构造函数std::string具有完全相同的效果,该构造函数采用对字符串const char*的调用结果。).c_str()

于 2012-02-27T22:22:59.620 回答
5

As I recall, this was discussed on c.l.c++.m some years ago, and Andrew Koenig (I think it was Andrew, anyway) said it was actually brought up during some meetings, but the idea of accepting a string was quickly conflated with the idea of accepting a wstring as well, and from there turned into a discussion about support for internationalized character sets in file names, and ... shortly after that the whole idea was dropped because it had opened a big can of worms nobody was prepared to deal with right then.

于 2012-02-28T00:59:48.610 回答
2

他们只是忘记了string在 C++03 中添加构造函数。现在已经解决了。这一次其他的事情都被遗忘了,比如make_unique。总有更多的事情可以做。C++03 也忘记为现在包含的函数模板指定默认参数。

编辑:正如@Charles 所说,它可能不是字面上的“忘记”,而是显然应该存在的东西,但由于某种原因没有指定。std::next/给出了进一步的例子std::prev,这是一个很大的解脱,and std::to_stringstd::stoi/d/ul/ull这又是完全合理的,但直到这个时候没有人有时间来指定它们。他们之前的缺席不一定有很深的原因。

于 2012-02-27T22:27:03.800 回答