The default constructor cannot be moved

I am new to C ++ 11 and wrote the following class where I would like it to support std::move :

 class X { public: X(int x) : x_(x) {} ~X() { printf("X(%d) has be released.\n", x_); } X(X&&) = default; X& operator = (X&&) = default; X(const X&) = delete; X& operator = (const X&) = delete; private: int x_; }; 

However, when I compile it with the -std=c++0x option, the compiler complains about the following:

 queue_test.cc:12: error: 'X::X(X&&)' cannot be defaulted queue_test.cc:13: error: 'X& X::operator=(X&&)' cannot be defaulted 

My questions:

  • I did something wrong, which prevents class X having a default move constructor?
  • If there is a class that we really cannot use by default for our move constructor, can I learn how to create a move constructor?

Thanks,

+6
source share
3 answers

From the GCC C ++ 0x page:

GCC C ++ 11 mode implements most of the C ++ 11 standard created by the ISO C ++ Committee. The standard is available from various national standardization bodies; Working papers prior to the release of the standards are available on the ISO C ++ Standard Committee website at http://www.open-std.org/jtc1/sc22/wg21/ Since this standard has only recently been completed, the feature set provided by the experimental C ++ 11 mode can vary greatly from one version of GCC to another. No, attempts will be made to maintain backward compatibility with the C ++ 11 function, whose semantics changed during the C ++ 11 standardization.

The std=c++11 flag was also introduced in GCC 4.7. From man gcc (I did not find it in info gcc ):

 c++11 c++0x The 2011 ISO C++ standard plus amendments. Support for C++11 is still experimental, and may change in incompatible ways in future releases. The name c++0x is deprecated. 

I suppose this means that in the latest version of the compiler, the flags are identical, but instead you should prefer c++11 to avoid possible errors.

From the info gcc command:

The default value, if C ++ dialects are not specified, is '-std = GNU ++, 98'.

This means c++98 with extensions.

+2
source

As follows from the comments, the error was caused by improper compiler settings. The option -std=c++11 should be used. (note that this is lowercase instead of uppercase, otherwise the compiler will complain about the following):

 g++: error: unrecognized command line option '-std=C++11' 
+2
source

This code compiled by GCC 4,8,1

In addition, there is the following example in the C ++ standard

 struct trivial { trivial() = default; trivial(const trivial&) = default; trivial(trivial&&) = default; trivial& operator=(const trivial&) = default; trivial& operator=(trivial&&) = default; ~trivial() = default; }; 

I did not find a place in the standard where it will be said that the move constructor cannot be installed by default.

+1
source

All Articles