我尝试创建输出计时结果并从预定义字符串调用任何 ofstream:
#include <cstring>
#include <map>
#include <fstream>
using namespace std;
int main(void) {
map<string,ofstream> Map;
ofstream ofs("test_output");
string st="test";
Map[st] = ofs;
return 0;
}
我收到以下错误;我该如何修复它?
a.cpp: In function ‘int main()’:
a.cpp:11:8: error: use of deleted function ‘std::basic_ofstream<_CharT, _Traits>& std::basic_ofstream<_CharT, _Traits>::operator=(const std::basic_ofstream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits<char>]’
Map[s]=ofs;
^
In file included from a.cpp:3:0:
/usr/include/c++/5/fstream:744:7: note: declared here
operator=(const basic_ofstream&) = delete;
^
In file included from a.cpp:3:0:
/usr/include/c++/5/fstream:744:7: note: declared here
operator=(const basic_ofstream&) = delete;
最佳答案
由于 std::ostream
不可复制(复制构造函数和赋值运算符被标记为已删除),因此您必须直接在映射中构造 ofstream(例如使用 std::map::emplace()
)或使用移 Action 业。
就地构建
基本上有两种方法,要么在映射中默认构造流(C++11 之前),要么调用 std::map::emplace()
提供 ofstream
构造函数参数。
使用默认构造(甚至可以在 C++11 之前使用):
map<string,ofstream> m;
// default-construct stream in map
ofstream& strm = m["test"];
strm.open("test_output");
strm << "foo";
使用安置:
// 1st parameter is map key, 2nd parameter is ofstream constructor parameter
auto res = m.emplace("test", "test_output");
auto& strm = res.first->second;
strm << "bar";
移动分配
我们可以先在map之外构建流,将其变成rvalue通过调用 std::move()
并使用move assignment operator将其移动到 map 中:
map<string,ofstream> m;
ofstream strm("test_output");
m["test"] = std::move( strm );
// strm is not "valid" anymore, it has been moved into the map
如果我们直接将流创建为 rvalue,我们甚至可以摆脱 std::move()
:
m["test"] = ofstream("test_output");
移动分配的效率低于其他方法,因为首先会在 map 中默认构造一个流,然后被移动分配的流替换。
Live demo of all three methods.
注意:为简洁起见,示例代码省略了任何错误处理。打开后和每次流操作后应检查流的状态。
关于c++11 - 我们不能管理 std::map<string,ofstream> 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42920744/