pic11
pic11

Reputation: 14993

Calling c_str of empty string

Is this code fragment OK or does it result in undefined behavior?

std::string s;
assert(strlen(s.c_str())==0);

If it isn't undefined behavior, will the above assertion pass?

Upvotes: 12

Views: 11957

Answers (3)

David Heffernan
David Heffernan

Reputation: 613451

That is perfectly well defined and the assertion passes. The c_str() function will always return a valid zero terminated C string.

One would normally use empty() to test for an empty string.

Upvotes: 13

Marcelo Cantos
Marcelo Cantos

Reputation: 186058

Yes it will work (if you append () to c_str to make it actually call the function) and the assertion will pass.

Upvotes: 6

user541686
user541686

Reputation: 210755

It's a compile error (if you have assertions enabled), since a const char *(std::string::*)(), cannot be converted to const char * implicitly.

(Tongue only halfway in cheek.)

Upvotes: 3

Related Questions