在clang的C++ 11状态页面中遇到了一个名为"rvalue reference for*this"的提案.
我已经阅读了很多关于rvalue引用并理解它们的内容,但我认为我不知道这一点.我也无法使用这些条款在网上找到太多资源.
页面上的提案文件有一个链接:N2439(将移动语义扩展到*this),但我也没有从中获得太多的例子.
这个功能是什么?
以下代码在Clang中编译,但在GCC中不编译.当我operator()使用左值调用时,它可以工作,但不能使用右值.为什么?
struct S
{
bool operator()() const & { return true; }
bool operator()() const && { return true; }
};
int main()
{
S s;
s(); // works
S()(); // fails (error: call of '(S) ()' is ambiguous)
}
Run Code Online (Sandbox Code Playgroud)
我正在GCC 4.8上编译这段代码.
假设我们有一个带有 2 个 xvalue 操作数的三元运算符。
struct A {
A() { std::cout<<"A ctor"<<std::endl; }
~A() { std::cout<<"A dtor"<<std::endl; }
A(A const&) { std::cout<<"A copy ctor"<<std::endl; }
A(A&&) { std::cout<<"A move ctor"<<std::endl; }
void foo() & { std::cout<<"A&.foo()"<<std::endl; }
void foo() const& { std::cout<<"A const&.foo()"<<std::endl; }
void foo() && { std::cout<<"A&&.foo()"<<std::endl; }
void foo() const&& { std::cout<<"A const&&.foo()"<<std::endl; }
};
int main()
{
A a;
A a2;
(true? static_cast<A&&>(a) : static_cast<A&&>(a2)).foo();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
根据cppreference条件运算符
4) 如果 E2 和 E3 是相同类型和相同值类别的左值,则结果具有相同类型和值类别,并且如果 E2 …