转换为 Type&& 运算符的类型

Type having conversion to Type&& operator

我很惊讶地看到以下编译:

struct C {
    operator C&&() {
        std::cerr << "ref'd\n";
        throw std::runtime_error("what is happening?");
    }
};

一种带有运算符的类型,用于其自身的右值引用转换。但是,我无法使用我认为可能会做的事情来调用操作员。将值传递给采用右值引用的函数失败,并且在对象上调用 std::move 不会触发任何内容。

为什么这段代码完全可以编译,有什么方法可以让这个函数真正实现 运行?

clang 给出 warning: conversion function converting 'C' to itself will never be used 有或没有类型的引用。

struct C
{
    operator C()
    {
    }
};

也是允许的,并给出相同的警告。在 §12.3.2/1 中提到:

A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.

换句话说,它没有被禁止,但它根本没有做任何事情。 Yakk 和 Wintermute 已经展示了成员函数调用语法的示例,但是 cppreference 展示了脚注 116 中提到的虚拟分派示例(N3337,N4140 中的脚注 118):

struct D;
struct B {
    virtual operator D() = 0;
};
struct D : B
{
    operator D() override { return D(); }
};

int main()
{
    D obj;
    D obj2 = obj; // does not call D::operator D()
    B& br = obj;
    D obj3 = br; // calls D::operator D() through virtual dispatch
}
void foo(C&&){}
int main(){
  C c;
  foo(c.operator C&&());
}

所以,基本没用,但也不完全。