[英]map insertions replaces previously entered values
我正在嘗試為用戶定義的類編寫一個容器。 我從文件中讀取密鑰並將其構造並插入到map中,但是當我在循環中這樣做時,雖然存在這些元素但它們都指向同一個對象...
正如您將在代碼中看到的那樣,我創建了一個“捕獲”,該“捕獲”從文件讀取以實例化“ Flux”並將它們存儲在地圖中。 問題在於,在循環內,插入的{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
我可能缺少明顯的東西,但我遠非專家,因此能提供任何幫助。 有人可以向我解釋這種行為嗎? 我只希望地圖包含配置文件中描述的不同通量。
Flux flux(cont.back(), cont.front(), pcap_prefix, max_pcap_size);
m_list_flux.emplace(cont.back(), flux);
您已在第二行發表評論:
這里插入的助焊劑代替了前一個:按鍵保持不變,但值已更改:我有幾個按鍵指向同一個對象...
您很幸運(不幸嗎?)這一切都奏效。 您正在存儲對該函數中創建的臨時Flux
對象的引用。 更改map
的類型以實際存儲它們,即可解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.