【问题标题】:Changes to class in setField() not being persistedsetField() 中对类的更改没有被持久化
【发布时间】:2014-03-08 01:20:40
【问题描述】:

我有一个类,如果它被正确插入到集合中,我试图设置一个值。这是那个类。

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&lt;flow&gt; 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;
}

完整性检查通过,值为打印。但是,稍后当我显示这些流时,不再设置该值。我怎样才能坚持这个价值?这个 currentFlow 与我的集合中持续存在的流不同吗?

如果您需要更多信息,请告诉我,我不想发布太多代码,但足以诊断问题。

【问题讨论】:

  • 相关:operator &lt; 的正确实现对于该设置正确运行是关键。确保确保它正在实施正确的strict weak ordering。
  • 如有必要,我可以发布它,但我能够检索正确的流程,并说明我是否已经在跟踪它。问题在于持久性。

标签: c++ class set getter-setter


【解决方案1】:

问题在于set::insert 创建了流对象的副本。因此,您对currentFlow 之后所做的任何更改

 ret = flows.insert(currentFlow); 

对实际存储在集合中的对象没有影响。

编辑: 正如马特麦克纳布(Matt McNabb)在下面提到的,人们应该意识到,这个问题不能通过简单地修改存储在流集中的副本来解决,因为这会使它的密钥无效(例如,阅读 what happens when you modify an element of an std::set? 以获取更多信息)

【讨论】:

  • 在此基础上,如果您尝试就地“编辑”集合中的对象,您应该非常小心;因为如果你做了一些改变它的顺序的事情,那么这个集合将处于无效状态,并且此后会发生故障。如果“键”可以与流程的“值”部分分开,请考虑使用map 而不是set。
  • @MattMcNabb 所以我也不能修改插入的那个?还是我误解了那个链接?如果我要使用集合而不是地图,我可以这样做吗?
  • @publ1c_stat1c C++11 制作std::set 迭代器const 是有原因的。
猜你喜欢
  • 2017-11-27
  • 2017-12-21
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 2020-02-14
相关资源
最近更新 更多