Reputation: 35982
// have compilation errors
class TestClass
{
public:
TestClass(std::string& str) {}
};
int main() {
TestClass tc(std::string("h"));
return 0;
}
p166.cpp: In function ‘int main()’:
p166.cpp:29:32: error: no matching function for call to ‘TestClass::TestClass(std::string)’
p166.cpp:25:3: note: candidates are: TestClass::TestClass(std::string&)
p166.cpp:23:1: note: TestClass::TestClass(const TestClass&)
// have NO compilation errors
class TestClass2
{
public:
TestClass2(const std::string& str) {}
};
int main() {
TestClass2 tc(std::string("h"));
return 0;
}
Question> Why the first part (TestClass) has compilation errors? Is it because that a NON-const reference cannot refer to a temporary object while a const-reference can refer to a temporary object?
Thank you
Upvotes: 0
Views: 444
Reputation: 131789
Is it because that a NON-const reference cannot refer to a temporary object while a const-reference can refer to a temporary object?
Yes, as simple as that. Temporary objects may bind to const references but not to non-const ones.
Note that in C++11, we get rvalue references (T&&
), which will only bind to rvalues (temporaries amongst other things). See this question for more info on lvalues, rvalues, and all those other things.
Upvotes: 4