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

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

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

(中继版本)拒绝:

#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构造函数?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

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

剑指Offer

剑指Offer

何海涛 / 电子工业出版社 / 2012-1 / 45.00元

《剑指Offer:名企面试官精讲典型编程题》剖析了50个典型的程序员面试题,从基础知识、代码质量、解题思路、优化效率和综合能力五个方面系统整理了影响面试的5个要点。全书分为7章,主要包括面试的流程,讨论面试流程中每一环节需要注意的问题;面试需要的基础知识,从编程语言、数据结构及算法三方面总结了程序员面试的知识点;高质量的代码,讨论影响代码质量的3个要素(规范性、完整性和鲁棒性),强调高质量的代码除......一起来看看 《剑指Offer》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

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

多种字符组合密码

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具