下面显示的源代码是检查Document类对象成员的一部分。 我们尝试创建一个Value类的对象,它是'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
答案 0 :(得分:1)
当GenericValue的赋值运算符使用移动语义时,会出现此行为。
以下是 rapidjson 中 GenericValue 的赋值运算符:
//! 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?