std::move真的能避免拷贝吗?关于其实际作用的技术疑问
关于std::move本质的疑问
- 我知晓
std::move(object)会返回该对象的右值引用。 - 但有观点称使用
push_back(std::move(object))替代push_back(object)可避免拷贝,这点我难以理解,以下示例似乎与之矛盾:
#include <utility> #include <iostream> #include <vector> #include <string> #include <iomanip> template <class T> void print(T const & object){ for (auto var : object){std::cout << ' '<<var;} std::cout << '\n'; } int main () { std::string foo = "foo-string"; std::string bar = "bar-string"; std::vector<std::string> myvector = { "super", "vip" , "pro" , "ok" }; // capcity=size=4; // this block is just to increase the capacity of the vector myvector.push_back( "rango" ); //NOW: capacity = 8 , size =5 std::cout << &myvector[0] <<'\n'; //check the address of the first element of the vector // this block is the point of the problem myvector.push_back(foo); // copies -> YES! myvector.push_back(std::move(bar)); // moves !?!? std::cout << "myvector contains:"; print(myvector); std::cout << &myvector[0] << '\n'; // re-check the address of first element of the vector = still the same. std::cout << "the moved-from object: " << std::quoted(bar); return 0; }
- 调用
push_back(std::move(object))前后,vector首元素地址未发生变化,这意味着新插入的末元素位置与首元素存在固定偏移。 - 既然如此,若不将对象拷贝到该固定位置,如何将对象的值存储到该位置?
内容的提问来源于stack exchange,提问作者Rango
相关产品推荐
相关产品推荐

