首页 > 解决方案 > Hand written move

问题描述

I have written a vector class to learn move semantics. I use move constructor to move T (commented line).

My question is why not to just copy all the bytes of temp object and set all bytes of temp object to zero like in C?

I know that the destructor will be called for temp object and it may require some initialized members to properly destruct. This can be reason why I must not change internal representation of the object.

But in case I'm 100% sure my ~T() don't have such requirements, is this a good optimization?

 20     void push_back(T&& val)
 21     {
 22         check_cap();
 23         //new (m_data + m_size) T(std::move(val));
 24         for(int i = 0; i < sizeof(T); ++i)
 25         {
 26             reinterpret_cast<char*> (m_data + m_size)[i] = reinterpret_cast<char*> (&val)[i];
 27             reinterpret_cast<char*> (&val)[i] = 0;
 28         }
 29         m_size++;
 30     }

(please don't tell anything about casts and their safety if it's not related to the actual question)

(I know it's not a good approach and better not to use it in real project. But I'm only interested how good is it from the point of efficiency.)

标签: c++c++11move-semanticsmemcpy

解决方案


why not to just copy all the bytes of temp object and set all bytes of temp object to zero like in C?

is this a good optimization?

I think not. Here's a quick-bench comparison between your hand written version and the normal version using clang++:

enter image description here

When using g++ the result is a tie, so no gain there either.


推荐阅读