SetField()中的类更改不持续
Changes to class in setField() not being persisted
本文关键字:SetField 更新时间:2023-10-16
我有一个我试图将其设置为一个值的类,如果将其正确插入到集合中。这是那个课。
class flow {
std::string source, dest, protocol, startTime; //
public:
flow() {}
flow(std::string & s, std::string & d, std::string p) :
source(s), dest(d), protocol(p) {}
bool operator==(const flow& rhs) const;
bool operator<(const flow& rhs) const;
bool setFields(std::string &, std::string &, std::string &);
std::string getSource() const;
std::string get_startTime() const;
//other getters not shown
void set_startTime(std::string &);
//other setters not shown
virtual ~flow();
std::string createKey() const;
};
bool flow::setFields(std::string & srcArg, std::string & destArg,
std::string & protocolArg) {
source = srcArg;
dest = destArg;
protocol = protocolArg;
return true;
}
void flow::set_startTime(std::string & a) {
startTime = a;
}
我有一组set<flow> flows;
。我将此流插入一个集合中。如果它无法插入,我知道我已经在跟踪此流程,但是如果不是,我想设置其开始时间。
flow currentFlow;
//...
protocol = string("TCP");
currentFlow.setFields(source, dest, protocol);
key = createKeyFromFlow(currentFlow);
ret = flows.insert(currentFlow); // see if we can insert this flow
if (ret.second == false) {
inserted = false;
// we failed to insert
it = ret.first; // "it" now points to element already in the set
} else {
string stringTS;
std::stringstream strstream;
//convert to string and store
strstream << currentTimeStamp;
strstream >> stringTS;
cout << stringTS << endl;
currentFlow.set_startTime(stringTS);
//sanity check to assert the value was set
cout << currentFlow.get_flow() << endl;
}
理智检查通过,值是打印的。但是,后来当我显示这些流程时,不再设置值。我如何坚持这个价值?这个电流流不在我的集合内持续存在的流程吗?
让我知道您是否需要更多信息,我不想发布太多的代码,但足以诊断问题。
问题是set::insert
创建了流对象的副本。因此,您对currentFlow
进行的任何更改
ret = flows.insert(currentFlow);
对实际存储在集合中的对象没有影响。
编辑:正如马特·麦克纳布(Matt McNabb)在下面提到的那样,应该注意,不能通过简单地修改存储在流集中的副本来解决此问题,因为这会使其密钥无效(例如,当您修改std :: set的元素时会发生什么情况?有关更多信息)