Implementing Move Constructor by Calling Move Assi

2019-02-01 00:50发布

问题:

The MSDN article, How to: Write a Move Constuctor, has the following recommendation.

If you provide both a move constructor and a move assignment operator for your class, you can eliminate redundant code by writing the move constructor to call the move assignment operator. The following example shows a revised version of the move constructor that calls the move assignment operator:

// Move constructor.
MemoryBlock(MemoryBlock&& other)
   : _data(NULL)
   , _length(0)
{
   *this = std::move(other);
}

Is this code inefficient by doubly initializing MemoryBlock's values, or will the compiler be able to optimize away the extra initializations? Should I always write my move constructors by calling the move assignment operator?

回答1:

[...] will the compiler be able to optimize away the extra initializations?

In almost all cases: yes.

Should I always write my move constructors by calling the move assignment operator?

Yes, just implement it via move assignment operator, except in the cases where you measured that it leads to suboptimal performance.


Today's optimizer do an incredible job at optimizing code. Your example code is especially easy to optimize. First of all: the move constructor will be inlined in almost all cases. If you implement it via move assignment operator, that one will be inlined as well.

And let's look at some assembly! This shows the exact code from the Microsoft website with both versions of the move constructor: manual and via move assignment. Here is the assembly output for GCC with -O (-O1 has the same output; clang's output leads to the same conclusion):

; ===== manual version =====           |   ; ===== via move-assig =====
MemoryBlock(MemoryBlock&&):            |   MemoryBlock(MemoryBlock&&):
    mov     QWORD PTR [rdi], 0         |       mov     QWORD PTR [rdi], 0
    mov     QWORD PTR [rdi+8], 0       |       mov     QWORD PTR [rdi+8], 0
                                       |       cmp     rdi, rsi
                                       |       je      .L1
    mov     rax, QWORD PTR [rsi+8]     |       mov     rax, QWORD PTR [rsi+8]
    mov     QWORD PTR [rdi+8], rax     |       mov     QWORD PTR [rdi+8], rax
    mov     rax, QWORD PTR [rsi]       |       mov     rax, QWORD PTR [rsi]
    mov     QWORD PTR [rdi], rax       |       mov     QWORD PTR [rdi], rax
    mov     QWORD PTR [rsi+8], 0       |       mov     QWORD PTR [rsi+8], 0
    mov     QWORD PTR [rsi], 0         |       mov     QWORD PTR [rsi], 0
                                       |   .L1:
    ret                                |       rep ret

Apart from the additional branch for the right version, the code is exactly the same. Meaning: duplicate assignments have been removed.

Why the additional branch? The move assignment operator as defined by the Microsoft page does more work than the move constructor: it is protected against self-assignment. The move constructor is not protected against that. But: as I already said, the constructor will be inlined in almost all cases. And in these cases, the optimizer can see that it's not a self assignment, so this branch will be optimized out, too.


This get's repeated a lot, but it's important: don't do premature micro-optimization!

Don't get me wrong, I also hate software that wastes a lot of resources due to lazy or sloppy developers or management decisions. And saving energy is not just about batteries, but also an environmental topic, which I am very passionate about. But, doing micro-optimizations prematurely doesn't help in that regard! Sure, keep the algorithmic complexity and cache friendliness of your large data in the back of your head. But before you do any specific optimization, measure!

In this specific case, I would even guess that you will never have to hand optimize, because the compiler will always be able to generate optimal code around your move constructor. Doing the useless micro-optimization now will cost you development time later when you need to change code in two places or when you need to debug a strange error that only happens because you changed code in only one place. And that is wasted development time that could rather be spent doing useful optimizations.



回答2:

I wouldn't do it this way. The reason for the move members to exist in the first place is performance. Doing this for your move constructor is like shelling out megabucks for a super-car and then trying to save money by buying regular gas.

If you want to reduce the amount of code you write, just don't write the move members. Your class will copy just fine in a move context.

If you want your code to be high performance, then tailor your move constructor and move assignment to be as fast as possible. Good move members will be blazingly fast, and you should be estimating their speed by counting loads, stores and branches. If you can write something with 4 load/stores instead of 8, do it! If you can write something with no branches instead of 1, do it!

When you (or your client) put your class into a std::vector, a lot of moves can get generated on your type. Even if your move is lightning fast at 8 loads/stores, if you can make it twice as fast, or even 50% faster with only 4 or 6 loads/stores, imho that is time well spent.

Personally I'm sick of seeing waiting cursors and am willing to donate an extra 5 minutes to writing my code and know that it is as fast as possible.

If you're still not convinced this is worth it, write it both ways and then examine the generated assembly at full optimization. Who knows, your compiler just might be smart enough to optimize away extra loads and stores for you. But by this time you've already invested more time than if you had just written an optimized move constructor in the first place.



回答3:

My C++11 version of the MemoryBlock class.

#include <algorithm>
#include <vector>
// #include <stdio.h>

class MemoryBlock
{
 public:
  explicit MemoryBlock(size_t length)
    : length_(length),
      data_(new int[length])
  {
    // printf("allocating %zd\n", length);
  }

  ~MemoryBlock() noexcept
  {
    delete[] data_;
  }

  // copy constructor
  MemoryBlock(const MemoryBlock& rhs)
    : MemoryBlock(rhs.length_) // delegating to another ctor
  {
    std::copy(rhs.data_, rhs.data_ + length_, data_);
  }

  // move constructor
  MemoryBlock(MemoryBlock&& rhs) noexcept
    : length_(rhs.length_),
      data_(rhs.data_)
  {
    rhs.length_ = 0;
    rhs.data_ = nullptr;
  }

  // unifying assignment operator.
  // move assignment is not needed.
  MemoryBlock& operator=(MemoryBlock rhs) // yes, pass-by-value
  {
    swap(rhs);
    return *this;
  }

  size_t Length() const
  {
    return length_;
  }

  void swap(MemoryBlock& rhs)
  {
    std::swap(length_, rhs.length_);
    std::swap(data_, rhs.data_);
  }

 private:
  size_t length_;  // note, the prefix underscore is reserved.
  int*   data_;
};

int main()
{
   std::vector<MemoryBlock> v;
   // v.reserve(10);
   v.push_back(MemoryBlock(25));
   v.push_back(MemoryBlock(75));

   v.insert(v.begin() + 1, MemoryBlock(50));
}

With a correct C++11 compiler, MemoryBlock::MemoryBlock(size_t) should only be called 3 times in the test program.



回答4:

I don't think you're going to notice significant performance difference. I consider it good practice to use the move assignment operator from the move constructor.

However I would rather use std::forward instead of std::move because it's more logical:

*this = std::forward<MemoryBlock>(other);


回答5:

It depends what your move assignment operator does. If you look at the one in the article you linked to, you see in part:

  // Free the existing resource.
  delete[] _data;

So in this context, if you called the move assignment operator from the move constructor without initialising _data first, you would end up trying to delete an uninitialized pointer. So in this example, inefficient or not, it's actually crucial that you do initialize the values.



回答6:

I would simply eliminate member initialization and write,

MemoryBlock(MemoryBlock&& other)
{
   *this = std::move(other);
}

This will always work unless the move assignment throw exceptions, and it typically doesn't!

Advantages of this styles:

  1. You don't need to worry about whether the compiler would doubly initialize the members, because that may vary in different environments.
  2. You write less code.
  3. You don't need to update it even if you add extra members to the class in the future.
  4. Compilers can often inline the move assignment, so the overhead of copy constructor would be minimal.

I think @Howard's post does not quite answer this question. In practice, classes often don't like copying, a lot of classes simply disable copy constructor and copy assignment. But most classes can be moveable even if they are not copyable.