【问题标题】:A different version of an overloaded function(const int* const&/&&) gets called when passing const int* and int*传递 const int* 和 int* 时调用不同版本的重载函数 (const int* const&/&&)
【发布时间】:2019-07-11 14:27:01
【问题描述】:

我在代码中遇到了一个错误,其中调用了错误的重载函数。

问题归结为:

void func(const int* const& ptr){
    std::cout << "LValue reference\n";
}
void func(const int* const&& ptr){
    std::cout << "RValue reference\n";
}

int main(){
    const int* ptr;

    func(ptr);

    return 0;
}

上面的代码按预期工作,它打印LValue reference。 但是,当我将const int* ptr 更改为int* ptr 时,程序会打印RValue reference。这对我来说很奇怪,因为我给它传递了一个确认的 LValue。 这让我相信某种隐式转换正在发生,它将它变成一个 RValue。我确实使用 Godbolt 编译器资源管理器进行了调查,乍一看,这会证实我的怀疑,但我对汇编一无所知,所以我不能肯定。

所以问题是:这里发生了什么?

【问题讨论】:

    标签: c++ pass-by-reference implicit-conversion rvalue lvalue


    【解决方案1】:

    int*const int* 的类型不同。由于它们不是同一类型,因此必须进行转换,因为您不能将引用绑定到不同的类型,因此它被声明为引用(处理派生对象时除外)。

    这意味着int* 用于创建一个临时的const int*,这个临时指针是一个右值。由于它是一个右值,因此将选择右值引用重载。

    【讨论】:

      猜你喜欢
      • 2010-11-11
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      相关资源
      最近更新 更多