gpt4 book ai didi

c++ - l-value ref限定成员函数和非限定成员函数之间的区别?

转载 作者:行者123 更新时间:2023-11-30 02:38:35 25 4
gpt4 key购买 nike

左值引用限定成员函数和非限定成员函数之间有区别吗?如果有,那是什么?

即,这两种声明 func() 的方式是否不同?

class Foo
{
void func();
void func() &;
};

我的意思不是“它们是否足够不同以允许重载解析”,因为当 func() 的两个版本都存在时,显然上述类无法编译。我的意思是,当包含 & 和不包含时,编译器的行为如何以及为何不同?

至少有一个区别,即引用限定函数(左值或右值类型)不能被非引用限定函数重载。来自current standard draft :

Member function declarations with the same name and the same parameter-type-list as well as member function template declarations with the same name, the same parameter-type-list, and the same template parameter lists cannot be overloaded if any of them, but not all, have a ref-qualifier.

...但如果这是唯一的区别,为什么要限制?即,为什么不能将 foo()&& 视为(不合格的)foo() 的有效覆盖?

最佳答案

它们是不同的。

Foo foo;
std::move(foo).func();

将调用 func() 但不会调用 func()&

类似地:

Foo make_foo() { return {}; }
make_foo().func();

仅适用于 void func() 签名,不适用于 void func()& 签名。

void func()& 意味着它只是对左值而非右值的有效调用。

关于c++ - l-value ref限定成员函数和非限定成员函数之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30677744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com