【发布时间】:2019-11-24 05:27:12
【问题描述】:
我正在尝试为用户定义的类编写容器。我从文件中读取密钥并在地图中构造和插入元素。但是当我在循环中这样做时,元素存在但它们都指向同一个对象......
正如您将在代码中看到的那样,我创建了一个“捕获”,它从文件中读取以实例化“通量”并将它们存储在地图中。 问题是在循环中,插入的 {key,value} 替换了以前的值:键仍然存在,但现在指向同一个对象..
我的 .h 文件来了:
class Flux;
class Capture
{
public:
Capture(pcpp::PcapLiveDevice* dev, std::string pcap_prefix, unsigned int max_pcap_size = 0);
~Capture();
private:
std::map<std::string,Flux&> m_list_flux;
};
class Flux
{
public:
Flux(std::string filter,std::string folder, std::string prefix, unsigned int max_pcap_size);
~Flux();
void print();
private:
std::string m_folder;
};
这是我的 .cpp:
Capture::Capture(pcpp::PcapLiveDevice * dev, std::string pcap_prefix, unsigned int max_pcap_size)
{
std::ifstream conf("flux.conf");
std::string line;
if (conf) {
std::vector<std::string> cont;
while (getline(conf, line)) {
boost::split(cont, line, boost::is_any_of(":"));
std::cout << "creating directory and flux: " << cont.back() << std::endl;
fs::create_directory(cont.front());
Flux flux(cont.back(), cont.front(), pcap_prefix, max_pcap_size);
m_list_flux.emplace(cont.back(), flux); //here the inserted flux replaces the previous one: the key remains intact but the value is changed: i have several keys pointing to the same object...
}
fs::create_directory("flux0");
Flux flux2("any", "flux0", pcap_prefix, max_pcap_size);
m_list_flux.emplace("any", flux2); // same here
}
for (auto&it : m_list_flux) {
std::cout << "launching flux: " << it.first << std::endl;
it.second.print();
}
}
这打印:
launching flux: 10.10.10.10
flux0
launching flux: 10.10.10.102
flux0
launching flux: any
flux0
我尝试过手动操作:
Capture::Capture(pcpp::PcapLiveDevice * dev, std::string pcap_prefix, unsigned int max_pcap_size)
{
Flux flux("10.10.10.10", "flux1", m_pcap_prefix, max_pcap_size);
m_list_flux.emplace("flux1", flux);
Flux test("10.10.10.102", "flux2", m_pcap_prefix, max_pcap_size);
m_list_flux.emplace("flux2", test);
Flux test2("any", "flux0", m_pcap_prefix, max_pcap_size);
m_list_flux.emplace("flux0", test2);
for (auto&it : m_list_flux) {
std::cout << "launching flux: " << it.first << std::endl;
it.second.print();
}
}
在这种情况下它工作正常:它打印:
launching flux: 10.10.10.10
flux1
launching flux: 10.10.10.102
flux2
launching flux: any
flux0
我的 conf 文件只包含:
flux1:10.10.10.10
flux2:10.10.10.102
我可能遗漏了一些明显的东西,但我远非专家,因此感谢您提供任何帮助。 有人可以向我解释这种行为吗?我只希望我的地图包含配置文件中描述的不同通量。
【问题讨论】:
-
std::map<std::string,Flux&>- 是什么让你将地图的映射类型设置为Flux&?