Why does the following code compile in C++11 and does not in C++03? (both gcc and cl)
#include <string>
#include <iostream>
#include <fstream>
int main(int argc, char* argv[]) {
const std::string t("Hello");
std::ofstream out(t);
}
Why don’t the C++03 streams accept std::string as the constructor parameter? Was this decision based on something or did it happen accidentally?
The code fails when compiled with a strictly conforming C++03 compiler because the constructor that takes a
std::stringwas only added in C++11.As to the question, “was it based on something smart”, as the interface was added, it can be inferred that there was no technical reason for it to be omitted.
It’s an addition of convenience as, if you have a
std::string, you can always call.c_str()to get a C string suitable for use with the old interface. (As the documentation in C++11 says , the constructors that takestd::stringhave exactly the same effect as calling the corresponding constructor which takes aconst char*with the result of calling.c_str()on the string.)