2

On this website there is an example of simple class with a move constructor.

How would a move constructor of a similar class look:

class MemoryPage
{
        std::vector<char> buff;

        public:
        explicit MemoryPage(int sz=512)
        {
                for(size_t i=0;i<sz;i++)
                        buff.push_back(i);
        }

};

would it be:

MemoryPage::MemoryPage(MemoryPage &&other)
{
        this->buff = std::move(other.buff);
}

?

Chris Drew
  • 14,926
  • 3
  • 34
  • 54
user2449761
  • 1,169
  • 13
  • 25
  • 4
    `std::vector` already implements move-semantics. You don't need to create a move-constructor yourself as the default one for `MemoryPage` will do what you want. – David G Feb 21 '15 at 22:17

1 Answers1

3

A conforming C++11 compiler will automatically create a move constructor for you (Visual Studio 2013 does not). The default move constructor will do a member-wise move and std::vector implements move-semantics so it should do what you want.

But yes, if for some reason you do need to define the move constructor yourself that looks correct. Although it is preferable to use the constructor initialization list and declare it noexcept:

MemoryPage::MemoryPage(MemoryPage &&other) noexcept : buff(std::move(other.buff)) { }
Community
  • 1
  • 1
Chris Drew
  • 14,926
  • 3
  • 34
  • 54