相关疑难解决方法(0)

为什么 const 临时绑定到右值引用参数?

我有以下功能:

void func(void * const &ptr)
{
    std::cerr << "const" << std::endl;
}

void func(void *      &&ptr)
{
    std::cerr << "mutable" << std::endl;
}

void* const func2()
{
    return nullptr;
}
Run Code Online (Sandbox Code Playgroud)

一个重载采用 const 引用参数,另一个采用可变右值引用。并且有一个返回 const 值的函数。

当我将该 const 临时值传递给函数时:

func(func2());
Run Code Online (Sandbox Code Playgroud)

我希望选择 const 重载。但相反,我得到:

mutable
Run Code Online (Sandbox Code Playgroud)

这怎么可能?为什么 const 返回值绑定到非 const rvalue 引用参数?

然而,当void*我将 const 传递struct给函数时,这不会发生:

struct A
{
};

void func(A const &a)
{
    std::cerr << "const" << std::endl;
}

void func(A      &&a)
{
    std::cerr << "mutable" << …
Run Code Online (Sandbox Code Playgroud)

c++ rvalue overload-resolution

2
推荐指数
1
解决办法
83
查看次数

标签 统计

c++ ×1

overload-resolution ×1

rvalue ×1