为什么我需要将默认引用参数定义为 const 以便为其分配一个左值?

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

本文关键字:分配 一个 默认 引用 const 定义 参数 为什么      更新时间:2023-10-16

>我用默认参数定义了一个函数:

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

正确的方式:

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

我想知道为什么const会有所作为?

我知道可以为const变量分配一个左值。他们是同一个问题吗?

const int a = 42;

添加重载。这是一个最简单、最容易解决的方法。

void resize(size_t n, std::string &s); 
//add overload
void resize(size_t n)
{
std::string s;
resize(n, s);
}