Domanda

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 option -std=c++0x, the compiler complains 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 are:

  1. Did I do something wrong which disallows class X to have a default move constructor?
  2. In case there exists a class that we really can't default its move constructor, can I know how should I develop its move constructor?

Thank you,

È stato utile?

Soluzione

From GCC's C++0x page:

GCC's C++11 mode implements much of the C++11 standard produced by the ISO C++ committee. The standard is available from various national standards bodies; working papers from before the release of the standard are available on the ISO C++ committee's web site 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 may vary greatly from one GCC version to another. No attempts will be made to preserve backward compatibility with C++11 features whose semantics have changed during the course of 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 take this to mean in the latest compiler version, the flags are identical, but you should prefer c++11 instead to avoid potential bugs.

From the info gcc command:

The default, if no C++ language dialect options are given, is '-std=gnu++98'.

This means c++98 with extensions.

Altri suggerimenti

As the comments suggest, the error was caused by incorrect compiler option. Option -std=c++11 should be used. (note that it is lower case instead of upper case, otherwise the compiler will complain the following):

g++: error: unrecognized command line option ‘-std=C++11’

This code is compiled by GCC 4,8,1

Also the C++ Standard has the following example

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

I have not found the place in the standard where there would be said that move constructor may not be defaulted.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top