Actually, it is possible to use a std::string with Windows API calls. But you have to resize
them rather reserve
them (see notes below for caveats!
using namespace std;
std::string path(MAX_PATH, '\0'); // fill with null chars
GetModuleFileName(NULL, &path, path.length());
cout << "module path (before resize) = \"" << path << "\n" << endl;
// this is needed to adjust the size to what it actually is,
// so operator<<, etc. behave correctly (the string works
// with what it knows the length to be, not the null term.)
cout << "module path = \"" << path << "\n" << endl;
module path (before resize) = "c:\test\test.exe
module path = "c\test\test.exe"
- using std::strings like this is offically sanctioned
(i.e. part of the standard) in C++11, as std::string's storage is now mandated to be contiguous, but not in C++03.
- while not previously part of the standard, all major implementations of std::string already use contiguous storage due to other requirements of the standard, so it was already a de facto
standard (which C++11 picked up). See Herb Sutter's comments on this (link below.)
(It's certainly safe to use this previously non-standard
approach with the std::string that ships with Visual C++. And if you're using C++11, it's totally fair game!)
- but usually, the C++ standard container of choice in this circumstance is std::vector<char>
, as std::vector's storage has always been guaranteed to be contiguous, allowing you to safely use, e.g.
// The preferred way
ReadFile(hFileIn, &buf[o], buf.size(), &BytesRead, FALSE);
PS See Herb Sutter's response to the question “What is with std::string?” on this page:
Cringe not: Vectors are guaranteed to be contiguous