I am having some valgrind issues when I write code like this:
static std::string function(std::string test)
{
size_t pos = test.find(',');
if (pos == test.npos)
{
// no comma
//
pos = test.length();
}
return test.substr(0, pos); //Valgrind is reporting possibly lost bytes here
}
Now my question is should I do this instead?
static std::string function(std::string test)
{
size_t pos = test.find(',');
if (pos == test.npos)
{
// no comma
//
pos = test.length();
}
static std::string temp = test.substr(0, pos);
return temp;
}
I think that having the string temp static is sort of important because function is static so anything that is returned by function should have the same lifetime as the object incapsulating function. Or is my analysis flawed?
Thank you
No, definitely not. No need to create such a temporary (and espcially not a
staticone, making the function non-reentrant, or in the end only working the first time in your case). Valgrind is reporting rubbish here, I guess. Your code looks fine like it is.Yes, it is. A
staticclass method doesn’t have an object associated with it, which could have a distinct lifetime, anyway (it’s like a normal non-class function, just that you need to scope it with the class name when calling). Other than that you don’t return a reference to any temporarystringanyway, but a new object copied fromtemp, so there are no lifetime problems to be taken into account here.Other than that, you might want to consider taking the
testobject by const-reference, since you don’t modify nor copy it (could this be related to general misunderstandings about object identity and object value?).