【问题标题】:How to allocate and return a string without memory leak in C++?如何在 C++ 中分配和返回没有内存泄漏的字符串?
【发布时间】:2015-01-29 21:46:49
【问题描述】:

假设我有 3 个功能:

int A(void); 
string B(const string& fileName); 
void C(string& dataFromFile);

A() 调用 B() 并使用 B() 的返回值作为 C() 的输入参数。在这种情况下,我想在 B() 中打开文件并将文件中写入的数据读取到缓冲区中。然后我想将此数据作为字符串返回。如何实现 B() 以避免内存泄漏?因为下面的伪代码会导致内存泄漏。

string B(const string& fileName) {
    // open file 
    char* buffer = new char[sizeOfFile];
    // read from file and assogn the data to buffer
    return buffer;
}

【问题讨论】:

  • 留在std::stringchar *。不要混合它们,否则你会遇到你面临的问题(以及更多)。您可以将文件读入std::string,这将解决您的问题;或者声明函数返回char *
  • 从缓冲区显式创建返回值字符串,然后删除缓冲区。字符串的缓冲区独立于 ctor 参数。
  • 文件是肯定全文?有多种方法可以做到这一点,this being one

标签: c++ memory-leaks return-value


【解决方案1】:

您可以只使用 std::string 避免任何泄漏。

std::string B(const std::string& fileName)
{
std::string buffer;
// open file
buffer.reserve(sizeOfFile);
// do stuff
return buffer;
}

编辑:使用reserve 预分配所需内存和return value optimization 与char* 相比,这不应该有巨大的性能损失。

【讨论】:

    【解决方案2】:

    跳过中间人。从一个字符串开始,读入字符串,然后返回字符串。我不确定您使用哪些函数来读取数据,但无论您可以使用char* 做什么,您都可以使用std::string。例如,如果您使用ifstreamread 函数,您可以这样做:

    std::string buffer;
    buffer.resize(sizeOfFile);
    fin.read(&buffer[0], sizeOfFile);
    return buffer;
    

    【讨论】:

    • 所以说这个版本不会造成任何内存泄漏,以及分配给缓冲区的内存会自动释放,是否安全?另一个问题:(我试图了解底层机制)std::string 有什么特别之处?例如,当我为嵌入式平台或定义了另一个字符串的任何平台编程时会发生什么?
    • @lulijeta:std::string 没有什么特别之处。它只有一个析构函数,可以清理它分配的任何资源,任何表现良好的类都应该这样做。也就是说,它遵循RAII
    【解决方案3】:

    将函数更新为:

    string B(const string& fileName) {
        // open file 
        char* buffer = new char[sizeOfFile];
        // read from file and assogn the data to buffer
    
        string ret(buffer);
        delete [] buffer;
        return ret;
    }
    

    如果您可以使用string 而不是char*,那就更好了。

    string B(const string& fileName) {
        // open file 
    
        strin ret(sizeOfFile, `\0');
        // read from file and assogn the data to ret
    
        return ret;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多