Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I get an Expression is not assignable error

Tags:

c++

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 * &

like image 953
thewoz Avatar asked Mar 04 '23 00:03

thewoz


2 Answers

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.

like image 189
Seva Alekseyev Avatar answered Mar 06 '23 14:03

Seva Alekseyev


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, or it++;

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.

like image 34
songyuanyao Avatar answered Mar 06 '23 14:03

songyuanyao