gpt4 book ai didi

c++ - std::ofstream 打开的 klocwork 问题

转载 作者:行者123 更新时间:2023-11-28 04:42:33 25 4
gpt4 key购买 nike

Klocwork throw

resource acquired to 'ofs.open("file.txt", std::ofstream::out)' may be lost here

对于下面的代码。

#include <iostream>
#include <fstream>

void main()
{
std::ofstream ofs;
ofs.open("file.txt", std::ofstream::out);
if (ofs.is_open())
{
std::cout << "file open success\n";
}
ofs.close();
}

我没有发现上述代码有任何问题。有人可以解释这里需要做什么来解决这个问题。

最佳答案

您是否还有这个问题?我有一个满足 Klocwork 的解决方法:使用 RAII:

std::ofstream ofs( "file.txt", std::ios::binary );

如果这不起作用,请使用临时工。

        std::ofstream temp( "file.txt", std::ios::binary );
if( !temp.is_open() )
{
temp.close();
}
else
{
m_outStream = std::move( temp );
}

关于c++ - std::ofstream 打开的 klocwork 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49927787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com