ofstream 无法在 Linux 上运行

2024-02-29

我有一个简单的测试代码:

#include <string>
#include <iostream>
#include <fstream>

int main() {
std::ofstream strm = std::ofstream("test.txt");
strm << "TEST123";
strm.close();
return 0;
}

if i compile this on windows it works perfectly. however when i compile it on debian with the following command: g++-4.7 -std=c++0x -lpthread TestStream.cpp -ldl -o TestStream than it gives the following output: enter image description here

我用谷歌搜索这个错误没有结果。有人知道如何解决这个问题吗?我在我的项目中使用了很多 ofstreams,并且也想在 Linux 上编译它。

编辑:所以我现在已经编译了,感谢 WinterMute,但是现在它打印空文件。我该如何解决?

EDIT2:不知道为什么,但第二次编译它有效。谢谢!


Use

std::ofstream strm("test.txt");

This:

std::ofstream strm = std::ofstream("test.txt");

需要一个复制构造函数std::ofstream没有或仅自 C++11 起可用的移动构造函数。 GCC 4.7 尚未完全支持 C++11,显然这是缺少的功能之一。

在评论中,T.C.提到可移动流直到版本 5 才会出现在 gcc 中,该版本计划于今年发布。这让我感到惊讶,因为 gcc 声称版本 4.8.1 完全支持 C++11——这对于编译器来说是正确的,但对于 libstdc++ 则不然。眼见为实。

所以也许值得一提的是libc++ http://libcxx.llvm.org/(与 clang 和 llvm 相关的 C++ 标准库实现)实现了可移动流,并且 clang 3.5 和 gcc 4.9(这些是我在这里尝试过的)都会编译原始代码(如果使用原始代码而不是 libstdc++)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ofstream 无法在 Linux 上运行 的相关文章

随机推荐