c++ 为什么在返回从函数的返回类型派生的类型的本地对象时,没有选择move构造函数?

栏目: C++ · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/40039379/why-is-move-constructor-not-picked-when-returning-a-local-object-of-type-derived
以下代码均被 ClangGCC

(中继版本)拒绝:

#include <memory>

struct Base 
{
    Base() = default; 
    Base(Base const&) = delete;
    Base(Base&&) = default;
};

struct Derived : Base
{
    Derived() = default; 
    Derived(Derived const&) = delete;
    Derived(Derived&&) = default;
};    

auto foo()
    -> Base
{
    Derived d;    
    return d;   // ERROR HERE
}

根据[class.copy] / 32:

When the criteria for elision of a copy/move operation are met, but not for an exception-declaration, and the object to be copied is designated by an lvalue, or when the expression in a return statement 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, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue

如果上面的句子意图被解析为(复制elision标准符合& lvalue)|| (id-expression指定一个自动对象),正如 this CWG defect 所示,为什么这不是最后一个条件呢?在Clang和GCC中是否有编译器错误?

另一方面,如果这个句子意图被解析为(copy elision criteria met&(lvalue || id-expression指定一个自动对象)),这不是一个非常误导性的字面意义吗?

[class.copy] / 32继续:

[…] 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.

第一个重载分辨率,以d作为值,选择Base :: Base(Base&&).然而,所选构造函数的第一个参数的类型不是派生和&但是Base&&&&&&&&&&&&&&&第二个重载分辨率选择删除的拷贝构造函数.

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/40039379/why-is-move-constructor-not-picked-when-returning-a-local-object-of-type-derived


以上所述就是小编给大家介绍的《c++ 为什么在返回从函数的返回类型派生的类型的本地对象时,没有选择move构造函数?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

调试九法

调试九法

David J.Agans / 赵俐 / 人民邮电出版社 / 2010-12-7 / 35.00元

硬件缺陷和软件错误是“技术侦探”的劲敌,它们负隅顽抗,见缝插针。本书提出的九条简单实用的规则,适用于任何软件应用程序和硬件系统,可以帮助软硬件调试工程师检测任何bug,不管它们有多么狡猾和隐秘。 作者使用真实示例展示了如何应用简单有效的通用策略来排查各种各样的问题,例如芯片过热、由蛋酒引起的电路短路、触摸屏失真,等等。本书给出了真正能够隔离关键因素、运行测试序列和查找失败原因的技术。 ......一起来看看 《调试九法》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

MD5 加密
MD5 加密

MD5 加密工具