vendredi 27 mars 2015

Difference between strlen(str.c_str()) and str.length() for std::string

As an implicit understanding, I always thought that every implementation of std::string necessarily must satisfy strlen(str.c_str()) == str.length() for every string str.


What does the C++ standard say about this? (Does it?)


Background: At least the implementations shipped with Visual C++ and gcc do not have this property. Consider this example (see here for a live example):



// Output:
// string says its length is: 13
// strlen says: 5
#include <iostream>
#include <cstring>
#include <string>

int main() {
std::string str = "Hello, world!";
str[5] = 0;
std::cout << "string says its length is: " << str.length() << std::endl;
std::cout << "strlen says: " << strlen(str.c_str()) << std::endl;
return 0;
}


Of course, the writing operation without str noticing is causing "the problem". But that's not my question. I want to know what the standard has to say about this behavior.


Aucun commentaire:

Enregistrer un commentaire