Consinder the following example:
#include <iostream>
#include <string>
struct foo { std::string value; };
inline foo bar() { return { "42" }; }
std::string my_func() {
auto &x = bar();
^^^^^^^^^^^^^^^^
return x.value;
}
int main() {
std::cout << my_func() << std::endl;
}
Compiling it both GCC and CLANG emit, most probably rightfully, the same error:
error: invalid initialization of non-const reference of type 'foo&' from an rvalue of type 'foo'
However, to my surprise it compiles and runs fine in VC++2015.
auto
can add implicitly const
ness to an object when a statement renders the program ill-formed?Is this a bug of VC++2015?
The standard allows implementations to accept code that is ill-formed as extensions. However implementations are still required to issue a diagnostic (which can just mean "emit a warning when certain flags are turned on").
Does the standard dictates that
auto
can add implicitly constness to an object when a statement renders the program ill-formed?
No, the standard requires auto
deduction to use the same rules as template argument deduction (with an exception for initializer lists). If T&
will not accept it, then auto&
will not.