ofstream constructor with std::string

I wrote some code and made a programming mistake, but it still worked. Later, when looking over the code I said to myself, "That shouldn't have compiled!".

I am running Microsoft Visual C++ 2010 Express.

Consider the following minimal code:
1
2
3
4
5
6
7
8
9
10
11
12
#include <fstream>
#include<string>

int main()
{
    std::string filespec = "D:/Temp/Test.txt";
    std::ofstream outFile( filespec );

    outFile << "Hello, World!\n";

    outFile.close();
}


The ofstream constructor should have been std::ofstream outFile( filespec.c_str() );

A std::string will also work with ofstream open() method.

Microsoft's documentation does not show this, either for the constructor or the open method. Nor is it listed as a language extension.

http://msdn.microsoft.com/en-us/library/y1et11xw%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/kexhtshc%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/34h23df8%28v=vs.100%29.aspx

For the open() method Intellisense shows eight methods including const std::string& and const std::wstring&.

I couldn't make Intellisense show me the available constructors, but clearly a constructor with const std::string exists.

I am not a professional programmer and don't have access to the C++ Standard.
Is this non-standard behavior or is this perhaps part of new Standard. I believe I would get compile time errors with VS C++ 2008 Express if I accidently passed a string instead of a char* as a parameter. Any comments?
Last edited on
I haven't look through all of the documentation of it so I can't tell you exactly where this is listed, but yes this was a new addition for C++11 (about time for this too).

This would not work on VS 2008 but no problems on VS 2010 as you saw.
Thanks for the response.
Topic archived. No new replies allowed.