Compiling with clang++ 4.1:
class A
{
public:
A(const char *s=0) : _s(s) {}
const char *_s;
};
void f(A a)
{
cout << a._s << endl;
}
int main()
{
f("test");
return 0;
}
prints,
test
whereas if I define f as follows,
void fA(A &a)
{
cout << a._s << endl;
}
I get a compilation error,
clang++ -std=c++11 -stdlib=libc++ -o test test.cpp
test.cpp:14:5: error: no matching function for call to 'f'
f("9000");
^
test.cpp:7:6: note: candidate function not viable: no known conversion from
'const char [5]' to 'A &' for 1st argument;
void f(A &a)
^
Why? I don’t understand why making f take a reference leads to problems.
f("test");attempts to create a temporaryA–f(A("test"));, but that temporary can’t bind to a non-const reference. The pass-by-value is okay because a copy is theoretically made (in practice, copy elision will occur).