const&和const&&的二义性

杨四正的源码剖析课
博客专家认证
2015-09-12 10:10:20
#include <iostream>
#include <memory>
#include <utility>

using namespace std;

class strange {
public:
mutable size_t count = 20;
strange() {
}

strange(const strange& o) :
count(o.count) {
cout << "strange(const strange& o)" << endl;
}

strange(const strange&& o) :
count(o.count) {
cout << "strange(const strange&& o)" << endl;
o.count = 0;
}

void testMethod(const strange&) {
cout << "testMethod(const &)" << endl;
}

void testMethod(const strange&&) {
cout << "testMethod(const &&)" << endl;
}

void testMethod(strange &) {
cout << "testMethod(&)" << endl;
}

void testMethod(strange &&) {
cout << "testMethod(&&)" << endl;
}
//==========================================
void testMethod() const& {
cout << "testMethod()const &" << endl;
}

void testMethod() & {
cout << "testMethod()&" << endl;
}

void testMethod() && {
cout << "testMethod()&&" << endl;
}

// OK:带来引用限定符...
void testMethod() const&& {
cout << "testMethod()const &&" << endl;
}
};

int main(int argc, char **argv) {
const strange s;
strange s2 = s;
strange s3 = move(s);

cout << s.count << endl;
cout << s2.count << endl;
cout << s3.count << endl;

s2.testMethod(move(s)); // OK...
s2.testMethod(s);// OK...
s2.testMethod(s2);// OK...
s2.testMethod(move(s2));// OK...

s2.testMethod();// OK...
s.testMethod();// OK...
strange().testMethod();// OK...
move(s).testMethod();// ERROR...
// error: call of overloaded 'testMethod()' is ambiguous
// note: candidates are:
// ..\src\Test3.cpp:40:7: note: void strange::testMethod() const &
// void testMethod() const& {
// ^
// ..\src\Test3.cpp:53:7: note: void strange::testMethod() const &&
// void testMethod() const&& {
// ^
return 0;
}

求解释,为什么作为参数的时候就没问题,作为成员函数的限定符的时候,就会出现二义性的问题?成员函数的限定符不是限定this的吗?不也是个参数吗?
...全文
298 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2015-09-14
  • 打赏
  • 举报
回复
不要纠结各种常量了,这个世界上唯一不变的就是变化。用API WriteProcessMemory还能修改正运行的其它进程的内存里面的所谓常量呢!
mujiok2003 2015-09-14
  • 打赏
  • 举报
回复
一般重载const T &和T&&就够了, 不要自己给自己找麻烦。
ri_aje 2015-09-13
  • 打赏
  • 举报
回复
引用 3 楼 xxxlxy2008 的回复:
[quote=引用 2 楼 ri_aje 的回复:] 软软的货吧?clang 3.6.1 和 gcc 4.9.2 都能够编译并输出 testMethod()const &&
g++ 4.8.1...这让我情何以堪啊![/quote] 呵呵,换 clang 吧。以后像这种情况多试几个编译器就行了。网上有很多在线编译的,还能选不同版本。
ri_aje 2015-09-12
  • 打赏
  • 举报
回复
软软的货吧?clang 3.6.1 和 gcc 4.9.2 都能够编译并输出 testMethod()const &&
ztenv 版主 2015-09-12
  • 打赏
  • 举报
回复
编译器的问题就规避吧,没必要深究的,估计升级后可能会解决
  • 打赏
  • 举报
回复
前面OK的输出如下:
strange(const strange& o)
strange(const strange&& o)
0
20
20
testMethod(const &&)
testMethod(const &)
testMethod(&)
testMethod(&&)
testMethod()&
testMethod()const &
testMethod()&&
  • 打赏
  • 举报
回复
引用 2 楼 ri_aje 的回复:
软软的货吧?clang 3.6.1 和 gcc 4.9.2 都能够编译并输出 testMethod()const &&
g++ 4.8.1...这让我情何以堪啊!

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧