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

后端 未结 3 1526
失恋的感觉
失恋的感觉 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 15:58

    One interesting application of this:

    void f(const std::string& x);
    std::string g() { return ""; }
    
    ...
    
    f(g() += "");
    

    Here, g() += modifies the temporary, which may be faster that creating an additional temporary with + because the heap allocated for g()'s return value may already have enough spare capacity to accommodate .

    See it run at ideone.com with GCC / C++11.

    Now, which computing novice said something about optimisations and evil...? ;-].

提交回复
热议问题