疑问
代码中希望使用std::move
提高效率,想探究std::move(*pointer)
的用法是否合理?
分析
这个问题不可一概而论,因为pointer
所指对象的类型会影响结果。
整数
#include <iostream>
int main()
{
int* p(new int(22));// a dumb pointer
int b(std::move(*p));
std::cout<<" b = "<<b<<std::endl;
std::cout<<"*p = "<<*p<<std::endl;
delete p;
return 0;
}
// Output:
// b = 22
// *p = 22
*p本质上返回右值引用(r-value reference)而int类型右值构造默认为copy因此原内存保留。
字符串
#include <iostream>
#include <string>
int main()
{
std::string* p(new std::string("22"));
std::string b(std::move(*p));
std::cout<<" b = "<<b<<std::endl;
std::cout<<"*p = "<<*p<<std::endl;
delete p;
return 0;
}
// Output:
// b = 22
// *p =
string类型内部实现了move construct因此原始对象会在move发生后被清除。
参考
std::move - cppreference.com
c++ - Should i delete a moved from dynamic pointer - Stack Overflow