Understanding Warning: Binding r value to l-value

I want to pass the structure by reference so that it is not copied, but Resharper gives a warning below:

struct sometype {
};

sometype foo() {
    sometype x;
    return x;
}

void bar() {
    sometype & a = foo();//Binding r-value to l-value reference is non-standard Microsoft C++ extension
    sometype && b = foo(); //ok
}

Questions:

What happened to sometype & a = foo();? is not a return value from an foo()lvalue and is aalso an lvalue?

Is the sometype && b = foo();rvalue reference really ? He "stole" the return value from foo()and sent what was in the bdestructor?

Is there any other way not to have this warning?

+4
source share
2 answers

You take a link to a temporary object. The only legal way to do this is:

const object& ( l),

object&& ( r-)

() .

:

, . , , :

{
  const string& s = foo();
  cout << s << endl;         // the temporary to which s refers is still alive
}
// but now it destroyed

, , , :

{
  string s& = foo();  // this is not possible
  s += "bar";         // therefore neither is this
  // the implication is that since you modified s, you probably want to
  // preserve it
}
// ... but now it destroyed and you did nothing with it.

, , , , :

string foo();         // function returning a string
void bar(string& s);  // this function is asserting that it intends to *modify*
                      // the string you sent it

// therefore:

bar(foo());           // makes no sense. bar is modifying a string that will be discarded.
                      // therefore assumed to be a logic error

:

  string s = foo();
  s += "bar";
  // do something here with s

, (l-value).

r-value , move move-assign. , . , .

, :

string&& s = foo();    // extends lifetime as before
s += "bar";
baz(std::move(s));     // move the temporary into the baz function.

, && , , .

, , , :

string foo();   // function that returns a string
void bar(string&& s);  // function that takes ownership of s

bar(foo());  // get a string from foo and move it into bar

// or more verbosely:

string s = foo();
bar(move(s));

++ 11, :

void bar(string s);   // copy a string

// resulting in:

const string& s = foo();
bar(s);  // extra redundant copy made here

void bar(const string& s); // const l-value reference - we *may* copy it
// resulting in:

const string& s = foo();
bar(s);  // maybe an extra redundant copy made here, it up to bar().
+6

sometype a = foo();

foo() , , ( ). - const sometype & a = foo(); rvalue.

sometype && b = foo(); rvalue reference?

( : rvalue ?)

"" foo() , b ?

,

?

: (1) rvalue, (2) const lvalue, (3) , .

, RVO .

+3

Source: https://habr.com/ru/post/1619628/


All Articles