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

查看所有标签

猜你喜欢:

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

Don't Make Me Think

Don't Make Me Think

Steve Krug / New Riders Press / 18 August, 2005 / $35.00

Five years and more than 100,000 copies after it was first published, it's hard to imagine anyone working in Web design who hasn't read Steve Krug's "instant classic" on Web usability, but people are ......一起来看看 《Don't Make Me Think》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具