c++ - 为什么在rapidjson中调用赋值运算符后成员变量发生变化?

标签 c++ rapidjson

下面显示的源代码是检查 Document 类对象成员的一部分。 我们试图创建一个值类的对象,即“memberObject”,并将对象引用存储到“_value”值引用私有(private)成员变量中。 查看输出,我们可以看到对象的类型是 3 (Object)。 但是,在使用 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

最佳答案

此行为是预期的,因为 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?

关于c++ - 为什么在rapidjson中调用赋值运算符后成员变量发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23070593/

相关文章:

c++ - 循环遍历多维数组

c++ - 组件-实体-系统 - 输入处理

c++ - 如何获取返回值并将其设置为 "x"?

c++ - 是否可以将 Thrift 代码转换为 Async

c++ - 如何编写用于rapidjson反序列化的嵌套处理程序?

c++ - KMDF 的多线程 DeviceIOControl

c++ - 将临时变量写入 Json : I get\u0000

c++ - rapidjson 正确的 json 创建

javascript - 使用 rapidjson 在 C++ 中比较 json 值

c++ - 如何在文件中添加 rapidjson::Document