简体   繁体   中英

Why I need to define a default reference parameter as const so that I can assign a lvalue to it? [duplicate]

This question already has an answer here:

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;

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM