复制vs std :: move int [英] copy vs std::move for ints

查看:134
本文介绍了复制vs std :: move int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 在该示例中,默认副本和std :: move有什么区别?
  • move之后,对象与新对象之间是否存在依赖关系?
  • What's difference between default copy and std::move in that example?
  • After move the object is there any dependence between new and old ones?
int main () {

    int a = 100;
    std::cout<<&a<<std::endl;

    auto a_copy = a;                 // deduced as int
    std::cout<<&a_copy<<std::endl;

    auto a_move = std::move(a);      // deduced as int
    std::cout<<&a_move<<std::endl;

};

输出:

0x7fffffffe094
0x7fffffffe098
0x7fffffffe09c

推荐答案

示例中,没有区别.我们最终得到3个int,其值为100.但是,不同类型肯定会有所不同.例如,让我们考虑类似vector<int>:

In this example, there is no difference. We will end up with 3 ints with value 100. There could definitely be a difference with different types though. For instance, let's consider something like vector<int>:

std::vector<int> a = {1, 2, 3, 4, 5}; // a has size 5
auto a_copy = a;                      // copy a. now we have two vectors of size 5
auto a_move = std::move(a);           // *move* a into a_move

最后一个变量a_move拥有a内部指针的所有权.因此,我们最终得到的是a_move是大小为5的向量,但是a现在为空. movecopy效率更高(想象一下,如果它是1000个字符串的向量-a_copy将涉及分配1000个字符串的缓冲区并复制1000个字符串,但是a_move只是分配了几个指针).

The last variable, a_move, takes ownership of a's internal pointers. So what we end up with is a_move is a vector of size 5, but a is now empty. The move is much more efficient than a copy (imagine if it was a vector of 1000 strings instead - a_copy would involve allocating a 1000-string buffer and copying 1000 strings, but a_move just assigns a couple pointers).

对于某些其他类型,可能无效:

For some other types, one might be invalid:

std::unique_ptr<int> a{new int 42};
auto a_copy = a;            // error
auto a_move = std::move(a); // OK, now a_move owns 42, but a points to nothing

对于许多类型,没有什么区别:

For many types, there's no difference though:

std::array<int, 100> a;
auto a_copy = a;            // copy 100 ints
auto a_move = std::move(a); // also copy 100 ints, no special move ctor

更一般地:

T a;
auto a_copy = a;            // calls T(const T& ), the copy constructor
auto a_move = std::move(a); // calls T(T&& ), the move constructor

这篇关于复制vs std :: move int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆