In Visual Studio 2012RC there are some non-standard extensions. For example this code compiles:
#include <string>
using namespace std;
void value(string& value)
{
value = "some";
}
int main()
{
value(string("nice"));
}
and get warning that it is non-standard extension. So, I want to understand, how it's real and how code transforms (rvalue-reference or const reference with const_cast)?
A temporary object of class type is still an object. It lives somewhere in memory, which means that there's nothing unusual in the compiler being able to attach a reference to it. At physical level whether it is a const reference or non-const reference makes no difference. In other words, in cases like that the language restriction is purely conceptual, artificial. The compiler simply ignores that restriction. There's no need to "transform" anything here. The reference is simply attached directly to the object, wherever that object happens to reside.
Basically, for a class that provides the outside word with access to the value of its this
pointer (or with lvalue access to *this
) the behavior can be immediately and easily simulated
struct S {
S& get_lvalue() { return *this; }
};
void foo(S& s);
...
foo(S().get_lvalue());
The above code is perfectly legal and it works around the aforementioned restriction. You can think of MSVC++ behavior as being equivalent to this.
Basically, VS will allocate the space somewhere and just let the reference point to it, as if it was a reference-to-const
without the constness (or in C++11 an rvalue reference).
You can disable this behaviour with the /Za
(disable language extensions) compiler switch under
Properties -> C/C++ -> Language
If I remember correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With