Binding r-value to l-value is a non-standard Microsoft C ++ extension

I was working on a project recently and I decided to install ReSharper C ++ in Visual Studio. When he parsed my code, he spat out a bunch of new warnings (apparently I have bad coding habits ..). One that took me time to figure out was Binding r-value to l-value reference is non-standard Microsoft C++ extension

. I have recreated the warning with the following code:

Type foo(Type t1, Type t2) {
    return Type(t1.value & t2.value);
}

      

The expression t1.value & t2.value

raises a warning. I understand the second part of the warning, which means that my code is only compiling due to the Microsoft extension, and other compilers will refuse to compile it. I am using an overloaded operator that returns an object (called Datum

) that Type

takes as a constructor parameter as a reference ( Type::Type(Datum& dat)

).

With some games, I managed to make the warning go away, refactoring the code:

Type bar(Type t1, Type t2) {
    Datum datum = t1.value & t2.value;
    return Type(datum);
}

      

As I understand it, this is functionally equivalent to the code that generated the warning. I would like to know if there is something here that I should be aware of, because I am rather confused as to why one function is complaining and the other is not.

I think I get it. I've already asked the question, so I'm going to post it with what I found for others to reference. I don’t have enough knowledge to understand in detail, so please feel free to expand or correct your answer if that is not satisfactory :)

+3


source to share


2 answers


This is one way to remove the warning: the variable is an lvalue, so it can bind directly to the parameter of the referenced reference constructor, while the expression evaluates to the value r, which cannot.

The best solution is to fix the constructor to accept its argument by value or a reference constant:



Type(Datum dat)         // value
Type(Datum const & dat) // constant reference

      

Now you can specify both an lvalue and an rvalue argument.

+6


source


From what I can see, the reason I got this behavior is because the constructor Type

takes a reference to an object Datum

rather than passing it by value. This raises a warning Type foo(Type, Type)

because the compiler does not like to refer to expressions that relate to expression evaluation semantics.



Again, please do not hesitate to refine or correct my results, as this is simply the result of my experiments and conclusions.

0


source







All Articles