涉及移动构造函数和 'Derived(Base&&)' 构造函数的 gcc 和 clang 之间的重载分辨率差异

Overload resolution difference between gcc and clang involving move constructor and 'Derived(Base&&)' constructor

GCC(使用 4.9 测试)接受以下测试用例:

struct Base {};

struct Derived : Base {
    Derived();
    explicit Derived(const Derived&);
    explicit Derived(Derived&&);
    explicit Derived(const Base&);
    Derived(Base&&);
};

Derived foo() {
  Derived result;
  return result;
}

int main() {
  Derived result = foo();
}

Clang(使用 3.5 测试)拒绝它并显示以下错误消息:

test.cpp:13:10: error: no matching constructor for initialization of 'Derived'
  return result;
         ^~~~~~
test.cpp:8:5: note: candidate constructor not viable: no known conversion from 'Derived' to 'Base &&' for 1st argument
    Derived(Base&&);
    ^
test.cpp:4:5: note: candidate constructor not viable: requires 0 arguments, but 1 was provided
    Derived();
    ^

谁说得对?

我相信 Clang 在这里是正确的。 GCC 不应接受该代码。

原因是 return 语句中发生的对象副本的构造函数重载解析的方式在 [class.copy] p32 中指定(强调我的):

When the criteria for elision of a copy/move constructor are met, [...], and the object to be copied is designated by an lvalue, [...], overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. If the first overload resolution fails or was not performed, or if the type of the first parameter of the selected constructor is not an rvalue reference to the object's type (possibly cv-qualified), overload resolution is performed again, considering the object as an lvalue.

在此示例中,符合省略条件([class.copy] p31 中的第一个项目符号)并且要复制的对象由左值指定,因此本段适用。

首先尝试重载解析,就好像对象是由右值指定的一样。 explicit 构造函数不是候选者(请参阅下文了解原因),因此选择了 Derived(Base&&) 构造函数。但是,这属于 "the type of the first parameter of the selected constructor is not an rvalue reference to the object's type"(相反,它是对对象基类型 class 的右值引用),因此应再次执行重载解析,将对象视为左值。

第二次重载解析失败,因为唯一可行的构造函数(同样,explicit 构造函数不是候选者)有一个右值引用参数,它不能绑定到左值。 Clang 显示生成的重载解析失败错误。


为了完成解释,这就是为什么 explicit 构造函数不是任一重载决议的候选者(所有重点都是我的)。

首先,[dcl.init] p15 说:

The initialization that occurs in the = form of a brace-or-equal-initializer or condition (6.4), as well as in argument passing, function return, throwing an exception (15.1), handling an exception (15.3), and aggregate member initialization (8.5.1), is called copy-initialization."

接下来,我们看[over.match.ctor] p1

For copy-initialization, the candidate functions are all the converting constructors (12.3.1) of that class.

最后,我们看到 explicit 构造函数没有转换 [class.conv.ctor] p1:

中的构造函数

A constructor declared without the function-specifier explicit specifies a conversion from the types of its parameters to the type of its class. Such a constructor is called a converting constructor.