Reputation: 14993
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
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
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
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