c++ - C++ std::move() performance wise with lvalues
问题描述
I've just finished learning about lvalues, rvalues, move constructor and move operator. I can see the added value of using move constructor with rvalues performance and usability wise. But i can't see the added value of using move operator with move constructor with lvalues performance wise, sure there is a added value usability wise, but can't we achieve the same functionality for lvalues using some other technologies like pointers for example. so my question is: what is the added value of using move operator with move constructor with lvalues performance wise. Thanks for reading my question.
example:
class string{
public:
char* data;
string(){
data = nullptr;
}
string(const char* p)
{
size_t size = std::strlen(p) + 1;
data = new char[size];
std::memcpy(data, p, size);
}
~string()
{
delete[] data;
}
string(const string& that)
{
size_t size = std::strlen(that.data) + 1;
data = new char[size];
std::memcpy(data, that.data, size);
}
string(string&& that)
{
data = that.data;
that.data = nullptr;
}
string movee(string &that){
data = that.data;
that.data = nullptr;
}};
what is the difference performence wise:
string s1("test");
string s2(std::move(s1));
string s1("test");
string s2 = string();
s2.movee(s1);
In the case of rvalues, the compiler spares us the time and memory taken to reform a new object and assign the rvalue to it, and then using that new object to change the values in the moved-to object, thus increasing performance. But in the case of a lvalue object, the move operator is not increasing performance, it is increasing usability and readability of course, but it is not increasing the performance as if it was a rvalue, am I wrong?
解决方案
您可以使用带有指针的间接来实现相同的功能。事实上,我们曾经,甚至现在,这正是您的移动构造函数/赋值运算符内部发生的事情!
是的,变量的大部分好处std::move
在于代码的清洁度。但这并非毫无意义。使用移动构造函数/赋值运算符窃取资源使我们能够巧妙、快速地完成此操作,而不会受到黑客攻击或任何性能损失。您的代码将更易于维护且更易于合理化。您将不太想添加一个额外的间接层,动态分配不需要动态分配的东西,只是为了获得任何可以理解的代码,因为现在这样做没有任何好处。
但!不要忘记您的标准容器在幕后为您执行此操作,例如在std::vector
调整大小时。这是非常有价值的。如果我们只能从临时人员那里搬走,那将是不可能的,我们将浪费大量机会。
用临时工做这件事并没有什么不同。只是它为您完成而无需键入std::move
。
推荐阅读
- git - 如何将两个 git 提交者合并到一个 GitLab 帐户中?
- python - PostgreSQL 查询给出了意想不到的结果
- docker - 从 dockerfile 运行 OCI CLI 命令
- c# - 使用 MS Graph 库发送带有大附件的电子邮件
- python - 如何覆盖定义类的命名空间?
- python - 以正确的方式将参数传递给 scipy minimzer
- scala - 以编程方式运行 scala 测试“规范”文件
- amazon-web-services - 我可以在 AWS 中的静态托管站点和动态托管站点之间使用反向代理吗?
- java - 在 Spring Boot 中为 catch 块添加代码覆盖率
- reactjs - 如何在 useEffect 运行之前测试组件?