I don't understand why I receive an "Expression is not assignable" error from the following code:
class value_t {
public:
int a;
};
class values_t {
public:
std::map<std::string, value_t *> list;
value_t * operator [] (const std::string & key) { return list[key]; }
value_t * get(const std::string & key) { return list[key]; }
};
int main(int argc, const char * argv[]) {
values_t values;
values.list["aaa"] = new value_t(); // OK
values["aaa"] = new value_t(); // ERROR
values.get("aaa") = new value_t(); // ERROR
return 0;
}
I don't see the difference between the second line of the main
function and the other.
How suggested the solution is to change the return type in value_t * &
values.list["aaa"]
returns a reference to a pointer, which can be assigned to.
values["aaa"]
and values.get("aaa")
return the pointer itself.
Change the return type of those two to value_t *&
and leave the implementation as it is.
operator []
and get
return value_t *
by-value, that means both values["aaa"]
and values.get("aaa")
are prvalue expressions, which can't be assigned.
a function call or an overloaded operator expression, whose return type is non-reference, such as
str.substr(1, 2)
,str1 + str2
, orit++
;
You might check what the return type of std::map::operator[]
, it's an lvalue-reference, then values.list["aaa"]
is an lvalue expression and can be assigned.
You can change their return type to value_t *&
to solve the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With