gpt4 book ai didi

c++ - 从右值引用到基的构造函数 - 可行(gcc)或不可行(clang) - 谁是对的

转载 作者:可可西里 更新时间:2023-11-01 18:38:12 25 4
gpt4 key购买 nike

最近有一个编译问题,用这个片段说明:

struct Base
{
};

template<typename T>
struct A : Base
{
A(){}
A(Base&&) {}
};

A<int> foo()
{
A<double> v;
return v;
}


int main()
{
auto d = foo();
return 0;
}

Gcc 说没问题,但 clang 不同意并说“候选构造函数不可行:对于第一个参数 A(Base&&) {},没有已知的从‘A’到‘Base &&’的转换”,请自行查看:https://godbolt.org/z/Y7mwnU

有哪位好心的读者能够提供一些标准术语来支持这两种观点吗?

最佳答案

clang 在这里是正确的。备案 87530 .

返回语句的规则是[class.copy.elision]/3 :

In the following copy-initialization contexts, a move operation might be used instead of a copy operation:

  • If the expression in a return statement ([stmt.return]) is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in the body or parameter-declaration-clause of the innermost enclosing function or lambda-expression, or
  • if the operand of a throw-expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) whose scope does not extend beyond the end of the innermost enclosing try-block (if there is one),

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. [ Note: This two-stage overload resolution must be performed regardless of whether copy elision will occur. It determines the constructor to be called if elision is not performed, and the selected constructor must be accessible even if the call is elided. — end note ]

强调我的。

我们遇到了第一个项目符号,我们正在返回一个 id-expression 来命名一个非 volatile 自动对象。所以我们执行重载决策,就好像它是一个右值一样。此重载解析成功,有一个构造函数采用 Base&&。但是,请注意粗体部分。此参数的类型不是对象类型的右值引用。

因此,我们再次尝试将该对象视为左值。此重载解析失败。

因此,该程序格式错误。

关于c++ - 从右值引用到基的构造函数 - 可行(gcc)或不可行(clang) - 谁是对的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52662407/

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