H
hingwah
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)
Thanks
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)
Thanks