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

查看所有标签

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

算法时代

算法时代

Luke Dormehl / 胡小锐、钟毅 / 中信出版集团 / 2016-4-1 / CNY 59.00

世界上的一切事物都可以被简化成一个公式吗?数字可以告诉我们谁是适合我们的另一半,而且能和我们白头偕老吗?算法可以准确预测电影的票房收入,并且让电影更卖座吗?程序软件能预知谁将要实施犯罪,并且精确到案发时间吗?这些事听起来都像是科幻小说中的情节,但事实上,它们仅是日益被算法主宰的人类世界的“冰山一角”。 近年来随着大数据技术的快速发展,我们正在进入“算法经济时代”。每天,算法都会对展示在我们眼......一起来看看 《算法时代》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具