On Apr 19, 11:22 pm, hing...@gmail.com wrote:
Consider the following code::
void log_function(const char *str); // 3rd party logging function
which don't use const std::string & as input
class Test
{
public:
std::string getDisplayString();};
int main()
{
Test obj;
const char * str = obj.getDisplayString().c_str();
log_function(str);;
return 0;
}
This yield undefined behaviour since the string object return
from getDisplayString() go out of scope in which the pointer
stored in variable str is no longer valid.
where as:
int main()
{
Test obj;
log_function(obj.getDisplayString().c_str());
return 0;
}
will work fine since the string return from obj.getDisplayString()
remain exist until log_function return;
sometimes this kind of bug is difficult to catch, and may just work
right fine until your application is in production.
Is there any tricks or any feature in C++0X to make this a
compile error catch by the compiler, e.g. some syntax to
indicate return value from the method invoke by temperatory
cannot be assigned to a variable. (though we still can't
prevent log_function to store its temporary pointer, but that
should be easier to catch)
Not really. In the case of std::string, the name was chosen
intentionally to make it easy to search for, which is really
what I'd suggest doing. Wrap your log_function in a function
which takes an std::string, and the uses of c_str should be very
rare in your code. Rare enough that you can verify each one
manually.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34