C++: is return value a L-value?

后端 未结 3 1542
失恋的感觉
失恋的感觉 2020-12-07 15:18

Consider this code:

struct foo
{
  int a;
};

foo q() { foo f; f.a =4; return f;}

int main()
{
  foo i;
  i.a = 5;
  q() = i;
}

No compile

3条回答
  •  天命终不由人
    2020-12-07 16:01

    Because structs can be assigned to, and your q() returns a copy of struct foo so its assigning the returned struct to the value provided.

    This doesn't really do anything in this case thought because the struct falls out of scope afterwards and you don't keep a reference to it in the first place so you couldn't do anything with it anyway (in this specific code).

    This makes more sense (though still not really a "best practice")

    struct foo
    {
      int a;
    };
    
    foo* q() { foo *f = new malloc(sizeof(foo)); f->a = 4; return f; }
    
    int main()
    {
      foo i;
      i.a = 5;
    
      //sets the contents of the newly created foo
      //to the contents of your i variable
      (*(q())) = i;
    }
    

提交回复
热议问题