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.)
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++:

When using g++ the result is a tie, so no gain there either.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With