c++ - 返回字符串的静态方法

标签 c++ string valgrind

当我写这样的代码时,我遇到了一些 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/

相关文章:

c++ - 获取 mp3 专辑封面图片的地址

c++ - valgrind/helgrind 在压力测试中被杀死

c++ - 查询时间/周期是针对所有核心/线程的序列化请求还是并行请求?

C++ 预处理器删除可变参数宏调用中的空格 (Solaris Studio 12.3)

Java:替换字符串中缺少的 Unicode 符号?

python - 如何通过最短到最长的匹配从头到尾替换文本

php - 使用 var_dump 时 string() “value"是什么意思

c - C 中多维数组的内存分配问题

c++ - 我如何理解我的 valgrind 错误消息?

c++ - atexit() 与独立的 CLang 未定义