Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

c++ - vector::push_back insists on using copy constructor though a move constructor is provided

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
", other.th );
  }

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

};



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

  return 0;
}

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.

The assignment operator works, since if I replace the body of main() with

branch a;
branch b;
b = a;

It will compile and run as expected.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...