c++ - 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.)
解决方案
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.
推荐阅读
- python - 递归获取FTP文件夹及所有子文件夹的元数据
- c# - 如何从 lambda 对 AWS API Gateway 进行 REST 调用?
- r - 如何根据R中的给定序列对向量进行排序
- python - 在 KV 文件中更改 Kivy 类属性
- javascript - 为什么从 shelljs 执行工作的 shell 脚本会停止执行?
- c# - 停止标签在 Timer.Tick 上闪烁
- java - 错误:引起:java.lang.NullPointerException
- excel - VBA 插入 rows_dynamic
- django - 如何进行查询以仅获取每个用户的数据
- .net - 制作一个旧项目以使用 nuget 包管理器并创建 package.config 文件