【问题标题】:Why I need to define a default reference parameter as const so that I can assign a lvalue to it? [duplicate]为什么我需要将默认引用参数定义为 const 以便我可以为其分配左值? [复制]
【发布时间】:2019-10-13 04:44:19
【问题描述】:

我已经定义了一个带有默认参数的函数:

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;

【问题讨论】:

  • 可能与此重复:stackoverflow.com/questions/27463785/…"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 谢谢。我想知道如果我使用移动复制构造将临时推回向量中会怎样?

标签: c++ constants lvalue


【解决方案1】:

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

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

【讨论】:

  • 我想使用resize函数重新分配一个对象的内存。那么如何重载函数呢?
  • 他的意思是有两个版本的resize。一个声明为void resize(size_t n),另一个声明为void resize(size_t n, std::string& s)
  • 好的,我明白了。谢谢。
猜你喜欢
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 2021-12-27
  • 2011-11-03
  • 2020-05-23
  • 1970-01-01
  • 2021-02-25
相关资源
最近更新 更多