0
// 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

q0987
  • 31,246
  • 61
  • 222
  • 356

1 Answers1

4

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.

Community
  • 1
  • 1
Xeo
  • 123,374
  • 44
  • 277
  • 381