vector :: push_back坚持使用复制构造函数,虽然提供了一个移动构造函数 [英] vector::push_back insists on using copy constructor though a move constructor is provided

查看:777
本文介绍了vector :: push_back坚持使用复制构造函数,虽然提供了一个移动构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从gcc收到一个奇怪的错误,无法找出原因。我做了下面的示例代码使问题更清楚。基本上,有一个类被定义,我为其复制构造函数和复制赋值运算符private,以防止意外调用它们。

I was receiving a strange error from gcc and cannot figure out why. I made the following example code to make the problem more clear. Basically, there is a class defined, for which I make its copy constructor and copy assignment operator private, to prevent calling them accidentally.

#include <vector>
#include <cstdio>
using std::vector;

class branch 
{
public:
  int th;

private:
  branch( const branch& other );
  const branch& operator=( const branch& other );

public:

  branch() : th(0) {}

  branch( branch&& other )
  {
    printf( "called! other.th=%d\n", other.th );
  }

  const branch& operator=( branch&& other )
  {
    printf( "called! other.th=%d\n", other.th );
    return (*this);
  }

};



int main()
{
  vector<branch> v;
  branch a;
  v.push_back( std::move(a) );

  return 0;
}



我希望这个代码可以编译,但是它失败了gcc。实际上gcc抱怨
branch :: branch(const branch&)is private,据我所知不应该调用。

I expect this code to compile, but it fails with gcc. Actually gcc complains that "branch::branch(const branch&) is private", which as I understand shouldn't be called.

因为如果我用

branch a;
branch b;
b = a;

它将按预期编译和运行。

It will compile and run as expected.

这是gcc的正确行为吗?如果是这样,上面的代码有什么问题?
任何建议对我有帮助。谢谢!

Is this a correct behavior of gcc? If so, what's wrong with the above code? Any suggestion is helpful to me. Thank you!

推荐答案

尝试在move构造函数的声明中加入noexcept。

Try adding "noexcept" to the declaration of the move constructor.

我不能引用标准,但是最近的gcc版本似乎要求复制构造函数是public或move constructor被声明为noexcept。无论noexcept限定符,如果你使复制构造函数公开,它将按照你期望的运行时。

I can't quote the standard, but recent versions of gcc appear to require either that the copy constructor be public or that the move constructor be declared "noexcept". Regardless of the "noexcept" qualifier, if you make the copy constructor public, it will behave as you expect at run-time.

这篇关于vector :: push_back坚持使用复制构造函数,虽然提供了一个移动构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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