0

I have defined a function with default parameter:

void resize(size_t n, std::string &s = std::string()); // error: initial value to non-const must be lvalue 

right way:

void resize(size_t n, const std::string &s = std::string());

I want to know why the const makes a difference?

I know that a const variable can be assigned an lvalue. Are they the same question?

const int a = 42;
Milo Lu
  • 3,176
  • 3
  • 35
  • 46
Zhen Yang
  • 83
  • 9
  • 4
    Possibly a duplicate of this: https://stackoverflow.com/questions/27463785/cant-pass-temporary-object-as-reference `"The idea is that a function taking a non-const reference parameter is stating that it wants to modify the parameter and allowing it to go back to the caller. Doing so with a temporary is meaningless and most likely an error."` – selbie Oct 13 '19 at 04:53
  • @selbie Thanks. And I want to know what if I use a move copy construction to push_back the temporary into vector? – Zhen Yang Oct 13 '19 at 05:12

1 Answers1

0

Add overload. That is a most simple, easy way to resolve.

void resize(size_t n, std::string &s); 
//add overload
void resize(size_t n)
{
    std::string s;
    resize(n, s);
}
yumetodo
  • 1,147
  • 7
  • 19