我正在尝试为用户定义的类编写一个容器。我从文件中读取密钥,然后将元素构造并插入到map中。但是当我在循环中这样做时,这些元素存在,但是它们都指向同一对象...
如您在代码中所见,我创建了一个“ Capture”,它从文件读取以实例化“ Flux”并将它们存储在地图中。 问题在于,在循环内,插入的{key,value}会替换以前的值:保留了键,但现在指向相同的对象。
.h文件放在这里:
In [1]: my_tensor = torch.arange(24).view(2, 3, 4)
Out[1]:
tensor([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]])
In [2]: my_tensor.sum(2)
Out[2]:
tensor([[ 6, 22, 38],
[54, 70, 86]])
In [3]: my_tensor.sum(-1)
Out[3]:
tensor([[ 6, 22, 38],
[54, 70, 86]])
这是我的.cpp:
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;
};
此打印:
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();
}
}
我的conf文件仅包含:
launching flux: 10.10.10.10
flux1
launching flux: 10.10.10.102
flux2
launching flux: any
flux0
我可能缺少明显的东西,但我远不是专家,因此我们将不胜感激。 有人可以向我解释这种行为吗?我只希望地图包含配置文件中描述的不同流量。
答案 0 :(得分:3)
Flux flux(cont.back(), cont.front(), pcap_prefix, max_pcap_size);
m_list_flux.emplace(cont.back(), flux);
您已在第二行发表评论:
这里插入的助焊剂代替了前一个:键保持不变但值已更改:我有几个键指向同一对象...
您很幸运(不幸吗?)这一切都奏效。您正在存储对该函数中创建的临时Flux
对象的引用。更改map
的类型以实际存储它们,即可解决问题。