I did a quick look through the C++17 Standard but I couldn't quite figure out how the following code somehow compiles when using -std=c++17
in both Clang and GCC.
It does NOT compile, however, if -std=c++17
is not set, as I expected.
The way I see it, the code calls the copy constructor of Test
, which has a non-const lvalue reference as parameter using an rvalue reference on line 21. This will attempt to bind the rvalue reference to the lvalue reference, which (as far as I know) is not allowed.
#include<iostream>
class Test
{
public:
Test() { std::cout << "Test()\n"; }
// Copy constructor with non-const parameter
Test(Test &t) { std::cout << "Test(Test&)\n"; }
};
Test fun()
{
std::cout << "fun() called\n";
Test t;
return t;
}
int main()
{
Test t1;
Test t2 = fun();
return 0;
}
What changed on C++17 that allowed this program to compile successfully?
Tested on Compiler Explorer with both Clang and GCC (latest versions): godbolt
Link for the non-c++17 version (which does not compile): godbolt