【问题标题】:std::move with inner objects - no match for call带有内部对象的 std::move - 不匹配调用
【发布时间】:2018-08-24 11:32:01
【问题描述】:

下面的代码无法编译。 主要:

#include "preset.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    SomeA a1(4);
    WrapA wA1(a1);
    WrapA wA2(std::move(wA1)); //fails to compile here
    return a.exec();
}

预设.h:

    #include <QDebug>
    class SomeA
    {
    public:
        SomeA(int l){val = l;}
        SomeA(const SomeA& original): val(original.val){qDebug()<<"sA copy;";}
        SomeA(SomeA&& original){std::swap(val, original.val); qDebug()<<"sA move;";}  
        SomeA operator = (const SomeA&);
        int val{0};
    };

    class WrapA
    {
    public:
        WrapA(SomeA obj): aObj(obj){}
        WrapA(const WrapA& original): aObj(original.aObj) {qDebug()<<"wA copy";}
        WrapA(WrapA&& original) {aObj(std::move(original.aObj)); qDebug()<<"wA move";} //no match for call (SomeA)(std::remove_reference<SomeA&>::type)
        SomeA aObj{0};
    };   

我想 std::move 不会从引用转换为右值。任何想法如何实现如此深的移动c-tor?我想我错过了什么,但不明白到底是什么

【问题讨论】:

  • 为什么不像复制构造函数那样把aObj的初始化放在初始化列表中?
  • 天哪,它有效,谢谢 =0。在之前的一些测试之后,我就这样离开了。但无论如何仍然无法理解为什么它在体内不起作用
  • 它不起作用,因为您无法在正文中初始化这样的成员。编译器将语法解释为在aObj 上调用operator(),但由于不存在而失败。
  • 它不起作用,因为您尝试使用对象aObj 作为函数SomeA 类没有函数调用运算符 (operator())。
  • 看起来很明显,谢谢。

标签: c++ move-semantics move-constructor stdmove


【解决方案1】:
 WrapA(WrapA&& original) {aObj(std::move(original.aObj)); qDebug()<<"wA move";}

你的意思是这样写

 WrapA(WrapA&& original) : aObj(std::move(original.aObj)) {qDebug()<<"wA move";}

另请参阅复制构造函数。

(应该已经有类似的问题了,但是我没找到。)

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 1970-01-01
    • 2015-09-21
    • 2021-11-02
    • 1970-01-01
    • 2021-06-10
    • 2022-01-23
    • 2011-05-04
    • 1970-01-01
    相关资源
    最近更新 更多