c ++删除移动赋值操作符编译问题 [英] c++ deleted move assignment operator compilation issues

查看:96
本文介绍了c ++删除移动赋值操作符编译问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使用gcc 4.8.0(mingw-w64)失败,并显示-O2 -std = c ++ 11 -frtti -fexceptions -mthreads

The following code fails with gcc 4.8.0 (mingw-w64) with -O2 -std=c++11 -frtti -fexceptions -mthreads

#include <string>

class Param
{
public:
    Param() : data(new std::string) { }

    Param(const std::string & other) : data(new std::string(other)) { }

    Param(const Param & other) : data(new std::string(*other.data)) { }

    Param & operator=(const Param & other) {
        *data = *other.data; return *this;
    }

    ~Param() {
        delete data;
    }

    Param & operator=(Param &&) = delete;


private:
    std::string * data;
};


int main()
{
    Param param;
    param = Param("hop");


    return 0;
}

使用已删除的函数'Param& Param :: operator =(Param&&)'
在行上:

With the error : error: use of deleted function 'Param& Param::operator=(Param&&)' On the line :


param = Param ;

param = Param("hop");

如果我删除了移动分配删除行,则编译得很好。

And compiles well if I remove the move assignment delete line.

应该没有默认的移动赋值运算符,因为有用户定义的复制构造函数,用户定义的复制赋值和析构函数,所以删除它不应该影响编译,为什么它失败?
为什么分配只不使用副本赋值?

There should be no default move assignment operator since there are user defined copy constructors, user defined copy assignment, and destructors, so deleting it should not affect the compilation, why is it failing? And why is the allocation simply not using a copy assignment?

推荐答案

您尝试在 main 中使用。通过显式地将其定义为已删除,您可以声明,同时说使用它是一个错误。因此,当您尝试从右值( Param(hop))分配时,编译器首先查看是否声明了移动赋值运算符。因为它是和是最好的匹配,它试图使用它,只是发现它被删除。因此错误。

The function you deleted is exactly the assignment operator you try to use in main. By explicitly defining it as deleted you declare it and at the same time say using it is an error. So when you try to assign from an rvalue (Param("hop")), the compiler first looks whether a move assignment operator was declared. Since it was and is the best match, it tries to use it, just to find that it was deleted. Thus the error.

这是另一个不使用特殊函数的机制的例子:

Here's another example of this mechanism which uses no special functions:

class X
{
  void f(int) {}
  void f(short) = delete;
};

int main()
{
  X x;
  short s;
  x.f(s);  // error: f(short) is deleted.
}

删除已删除的 f c $ c>将导致编译器选择未删除的 f(int),因此无错编译。

Removing the deleted f(short) will cause the compiler to select the non-deleted f(int) and thus compile without error.

这篇关于c ++删除移动赋值操作符编译问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆