On Sat, Jun 2, 2012 at 1:06 AM, Hal Finkel <[email protected]> wrote: > Sam, > > Two quick questions: > > 1. Do you check the return type of c_str() to make sure it matches what > you expect? If you do check the type and it does not match, you should > also check if the returned type has a conversion operator to the type > needed. > > 2. Does this handle wide-character strings? > > I like the idea of adding this note, I think it will be helpful for > many users. > > -Hal > > On Fri, 1 Jun 2012 14:59:42 -0700 > Sam Panzer <[email protected]> wrote: > > > Hi, > > > > We had a request for more user-friendly printf() diagnostics, which > > asked for a note suggesting a call to .c_str() when passing a c++ > > string to printf when a char* is expected, and I thought it would > > make a good first submission: > > > > Currently code such as > > > > > > string foo; > > > > > > printf("Oh dear %s", foo); > > > > > > produces a reasonable (if somewhat technical) diagnostic: > > > > > > error: cannot pass object of non-trivial type 'string' (aka > > >> 'basic_string<char>') through variadic function; call will abort > > >> at runtime [-Wnon-pod-varargs] > > > > > > printf("Oh dear %s", foo); > > > > > > > > >> That confuses some people (such as people who happened to be > > >> sitting near me today). It would be easy for them to understand > > >> if this could special-case the situation where the call is to a > > >> *printf-like function and the non-POD in question is a string (or > > >> std::string), to suggest that the solution might be to add the > > >> missing ".c_str()". > > > > > > > > >> When format string checking is active for the function/argument in > > >> question it would also be possible to report on the expected > > >> argument type. > > > > > > > > >> (Of course it's also not ideal to report that the "call will abort > > >> at runtime" when generating an error rather than a warning, but > > >> that might not be worth fixing.) > > > > > > > > I attached a patch which emits this note when an object defining > > a .c_str() member function is passed instead of a char*, along with a > > test file. Searching for c_str() was intended to allow the note to > > fire for std::string replacements. > > > > -Sam > <http://lists.cs.uiuc.edu/mailman/listinfo/cfe-commits> >
One note: c_str() is supposed to return a `char const*` and the conversion from `char const*` to `char*` is deprecated. -- Matthieu
_______________________________________________ cfe-commits mailing list [email protected] http://lists.cs.uiuc.edu/mailman/listinfo/cfe-commits
