In Qt's JSON implementation, in the QJsonObject
class, there are two implementations of an operator (documentation here):
QJsonValue QJsonObject::operator[](const QString & key) const;
QJsonValueRef QJsonObject::operator[](const QString & key);
First off, what is the advantage here by returning QJsonValueRef
as opposed to returning QJsonValue
? Second, which value would be returned if I just said something like root['time']
, where root
is a QJsonObject
?
You should avoid asking more than one question in a submitted question. That being said, here are the answers for your questions:
Returns a reference to the value for key.
The return value is of type QJsonValueRef, a helper class for QJsonArray and QJsonObject. When you get an object of type QJsonValueRef, you can use it as if it were a reference to a QJsonValue. If you assign to it, the assignment will apply to the element in the QJsonArray or QJsonObject from which you got the reference.
This means, you could call a method on the return value without having an interim object created explicitly by you in the code, just like how references work in C++.
As for the second sub-question, it depends on what the root object is. If it is a const object, the second, the non-const version, could not be called since that would violate the const correctness. Note the const here at the end:
> QJsonValue QJsonObject::operator[](const QString & key) const;
^^^^^
For a mutable, aka. non-const object, you could call both, but by default the second version would be called. With some const casting, this could be changed, however.