当我写这样的代码时,我遇到了一些 valgrind 问题:
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
}
现在我的问题是我应该改为这样做吗?
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;
}
我认为字符串 temp
是静态的有点重要,因为 function
是静态的,所以 function
返回的任何东西都应该有与封装 function
的对象相同的生命周期。还是我的分析有缺陷?
谢谢
最佳答案
Now my question is should I do this instead?
不,绝对不是。无需创建这样的临时文件(尤其不是 static
临时文件,使函数不可重入,或者最后只在您的情况下第一次工作)。 Valgrind 在这里报告垃圾,我猜。您的代码看起来不错。
Or is my analysis flawed?
是的,是的。一个 static
类方法没有与之关联的对象,它可能有一个不同的生命周期,无论如何(它就像一个普通的非类函数,只是你需要用类名来限定它的范围调用时)。除此之外,您不会返回对任何临时 string
的引用,而是从 temp
复制的新对象,因此这里没有要考虑的生命周期问题.
除此之外,您可能需要考虑通过 const-reference 获取 test
对象,因为您不会修改或复制它(这可能与对对象身份和对象的一般误解有关值?)。
关于c++ - 返回字符串的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14633446/