【问题标题】:Why does the member variable change after invoking the assignment operator in rapidjson?为什么在rapidjson中调用赋值运算符后成员变量会发生变化?
【发布时间】:2014-04-14 21:17:44
【问题描述】:

下面显示的源代码是检查 Document 类对象成员的一部分。 我们试图创建一个值类的对象,即“memberObject”,并将对象引用存储到“_value”值引用私有成员变量中。 查看输出,我们可以看到对象的类型是 3(对象)。 但是,使用 memberObject 分配 _value 引用变量后,输出显示类型更改为 0 (NULL)。 我们希望这样的类型更改不应该发生。 你能解释一下为什么会这样吗?

  for (Value::MemberIterator itr = _document.MemberBegin(); itr != _document.MemberEnd(); itr++)
  {
        _itr = itr;

        _name = itr->name.GetString();
        _objectTypeID = (int)itr->value.GetType();

        cout << "Member [" << _name << "] - type is [" << _objectTypeID << "]" << endl;

        _typeID = _objectTypeID;

        if (itr->value.IsObject())
        {
              Value& memberObject = _document[_name.c_str()];
              cout << "Value type(1): " << memberObject.GetType() << endl;

              _value = (Value&)memberObject;
              cout << "Value type(2): " << memberObject.GetType() << endl;
        }


        _st.push(_itr);

        parseValue();

        _itr = _st.top();  // returns the next element in the stack
        _st.pop();         // removes an element from the stack
  }

"firmwareSettings": {
    "manageFirmware": false,
    "firmwareBaselineUri": ""
},

成员 [firmwareSettings] - 类型为 [3]
值类型(1):3
值类型 (2):0

【问题讨论】:

    标签: c++ rapidjson


    【解决方案1】:

    此行为是预期的,因为 GenericValue 的赋值运算符使用 移动语义

    这是 rapidjsonGenericValue 的赋值运算符:

     //! Assignment with move semantics.
        /*! \param rhs Source of the assignment. It will become a null value after assignment.
        */
        GenericValue& operator=(GenericValue& rhs) {
            RAPIDJSON_ASSERT(this != &rhs);
            this->~GenericValue();
            memcpy(this, &rhs, sizeof(GenericValue));
            rhs.flags_ = kNullFlag;
            return *this;
        }
    

    memberObject 被赋值给 _value 时,赋值运算符开始改变 flags_ 成员,它是 GetType() 返回的值右值对象的方法。

    有关移动语义的更多详细信息,请参阅What are move semantics?

    【讨论】:

      猜你喜欢
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多