I have just realized something disturbing. Every time I have written a method that accepts a std::string
as a paramater, I have opened up myself to undefined behaviour.
For example, this...
void myMethod(const std::string& s) {
/* Do something with s. */
}
...can be called like this...
char* s = 0;
myMethod(s);
...and there's nothing I can do to prevent it (that I am aware of).
So my question is: How does someone defend themself from this?
The only approach that comes to mind is to always write two versions of any method that accepts an std::string
as a parameter, like this:
void myMethod(const std::string& s) {
/* Do something. */
}
void myMethod(char* s) {
if (s == 0) {
throw std::exception("Null passed.");
} else {
myMethod(string(s));
}
}
Is this a common and/or acceptable solution?
EDIT: Some have pointed out that I should accept const std::string& s
instead of std::string s
as a parameter. I agree. I modified the post. I don't think that changes the answer though.
c_str
property? – Mason Wheeler Dec 08 '13 at 19:05c_str()
. I read (but don't have handy) that the initialization ofstd::string
with0
leads to undefined behaviour. – John Fitzpatrick Dec 08 '13 at 19:08char* s = 0
is undefined. I've seen it at least a few hundred times in my life (usually in the form ofchar* s = NULL
). Do you have a reference to back that up? – John Fitzpatrick Dec 08 '13 at 19:14std:string::string(char*)
constructor – ratchet freak Dec 08 '13 at 19:15const std::string&
for that parameter...?) – Grimm The Opiner Dec 09 '13 at 15:46const string&
there unless there's a reason not to, which this snippet doesn't have. – John Fitzpatrick Dec 09 '13 at 18:00string
as a parameter isn’t ideal because passing a literal implies an extra allocation and copy. The best solution isboost::string_ref
, which will be standardised in C++14 asstd::string_ref
. – Jon Purdy Dec 13 '13 at 12:000
(orNULL
ornullptr
), is nothing particular here, I think. Any pointer can potentially produce an error if there is no terminating character\0
somewhere after. So anything that was not generated withchar w[] = "string"
or manipulated carefully is potentially problematic for thestd::string
constructor. – alfC Jan 21 '15 at 05:13