Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++11 Can';我们管理std::map<;字符串,ofstream>;?_C++11_Ofstream - Fatal编程技术网

C++11 Can';我们管理std::map<;字符串,ofstream>;?

C++11 Can';我们管理std::map<;字符串,ofstream>;?,c++11,ofstream,C++11,Ofstream,我尝试创建用于输出计时结果的函数,并从预定义字符串调用任何流: #include <cstring> #include <map> #include <fstream> using namespace std; int main(v

我尝试创建用于输出计时结果的函数,并从预定义字符串调用任何流:

#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;
}
#包括
#包括
#包括
使用名称空间std;
内部主(空){
地图;
ofs流(“测试输出”);
string st=“test”;
Map[st]=ofs;
返回0;
}
我得到了以下错误;我怎样才能修好它

a.cpp:在函数“int main()”中:
a、 cpp:11:8:错误:使用删除的函数“std::basic_of stream&std::basic_of stream::operator=(const std::basic_of stream&)[带_CharT=char;_Traits=std::char_Traits]”
Map[s]=ofs;
^
在a.cpp中包含的文件中:3:0:
/usr/include/c++/5/fstream:744:7:注意:此处声明
运算符=(const basic_of stream&)=删除;
^
在a.cpp中包含的文件中:3:0:
/usr/include/c++/5/fstream:744:7:注意:此处声明
运算符=(const basic_of stream&)=删除;

这是因为您不能复制
ostream
您只能移动它。由于复制分配运算符被删除,因此出现此错误。相反,映射必须拥有流的所有权:

Map[st] = std::move(ofs);
现在这也意味着在迭代地图时必须小心。你必须避免复制,也要避免从地图上窃取所有权


在旁注中,请注意
使用名称空间std

由于
std::ostream
不可复制(复制构造函数和赋值运算符标记为删除),您必须直接在映射中构造ofstream(例如使用)或使用移动赋值

就地施工 基本上有两种方法,一种是映射中的默认构造流(C++11之前),另一种是调用提供流的
构造函数参数

使用默认构造(即使在C++11之前也适用):

如果我们直接将流创建为:

移动分配的效率低于其他方法,因为首先在映射中默认构造一个流,然后被移动分配的流替换


注意:为简洁起见,示例代码省略了任何错误处理。打开流后和每次流操作后都应检查流的状态。

流不能复制,您需要复制它。移动不是唯一的解决方案。@zett42事实上,可以使用带有(智能)指针的方法(并具有处理多态性的附加好处)。这不是我所想的,看到我的答案了。很高兴在这里看到更一般的答案。谢谢@zorutic I添加了更简单的移动分配示例:
m[“test2”]=ofstream(“test_输出”)
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<string,ofstream> m;    
ofstream strm("test_output");
m["test"] = std::move( strm );
// strm is not "valid" anymore, it has been moved into the map
m["test"] = ofstream("test_output");