下面的代码是否容易出现内存泄漏?

Apo*_*hay 5 c++ pointers

我是C++的新手,我想知道下面的代码是否容易出现内存泄漏.这里我使用std::ostream指针将输出重定向到控制台或文件.为此,我打电话给新的运营商std::ofstream.

#include <iostream>
#include <fstream>

int main() {
    bool bDump;

    std::cout << "bDump bool" << std::endl;
    std::cin >> bDump;

    std::ostream *osPtr;

    if (bDump) {
        osPtr = new std::ofstream("dump.txt");
    } else {
        osPtr = &std::cout;
    }

    *osPtr << "hello";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

还有一件事,我没有关闭我在调用构造函数时打开的文件ofstream.我们是否有任何潜在的数据丢失情况.因为文件没有关闭.

Mah*_*dsi 7

是.当然.你new没有打电话的时候delete,就会有内存泄漏.

代码执行后,您需要添加以下内容:

        if(bDump)
        {
            delete osPtr;
        }
Run Code Online (Sandbox Code Playgroud)

  • @lvella:在`main`结束时,内存无法恢复. (3认同)
  • 如果你不调用析构函数,那么我会认为资源泄露了.如果对象是空间站的链接会发生什么.如果你不干净地关闭连接,我相信NASA会非常生气. (2认同)

Mar*_*ork 5

由于@Mahmoud Al-Qudsi提到任何你新的东西也必须删除否则它将被泄露.

在大多数情况下,你根本希望使用删除,而是要使用智能指针自动删除对象.这是因为在异常的情况下你可以再次泄漏内存(而RAII)智能指针将保证删除对象,从而调用析构函数.

在析构函数中调用是很重要的(特别是在这种情况下).如果不调用析构函数,则可能不会将流中的所有内容刷新到基础文件.

#include <iostream>
#include <fstream>

int doStuff()
{
    try
    {
        bool bDump;

        std::cout<<"bDump bool"<<std::endl;
        std::cin>>bDump;

        // Smart pointer to store any dynamic object.
        std::auto_ptr<std::ofstream>   osPtr;

        if(bDump)
        {
            // If needed create a file stream
            osPtr.reset(new std::ofstream("dump.txt"));
        } 

        // Create a reference to the correct stream.
        std::ostream&  log = bDump ? *osPtr : std::cout;

        log << "hello";
     }
     catch(...) {throw;}

 } // Smart pointer will correctly delete the fstream if it exists.
   // This makes sure the destructor is called.
   // This is guaranteed even if exceptions are used. 
Run Code Online (Sandbox Code Playgroud)