C++ 移动迭代器和 int 向量 [英] C++ move iterator and int vector

查看:56
本文介绍了C++ 移动迭代器和 int 向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解移动迭代器.这是来自 https://en.cppreference.com/w/cpp/的示例代码迭代器/make_move_iterator

I am trying to understand the move iterator. This is the sample code from https://en.cppreference.com/w/cpp/iterator/make_move_iterator

#include <iostream>
#include <list>
#include <vector>
#include <string>
#include <iterator>
 
int main()
{
    std::vector<std::string> s{"one", "two", "three"};
 
    std::vector<std::string> v1(s.begin(), s.end()); // copy
 
    std::vector<std::string> v2(std::make_move_iterator(s.begin()),
                                std::make_move_iterator(s.end())); // move
 
    std::cout << "v1 now holds: ";
    for (auto str : v1)
            std::cout << "\"" << str << "\" ";   //return one, two, three
    std::cout << "\nv2 now holds: ";
    for (auto str : v2)
            std::cout << "\"" << str << "\" ";   //return one, two, three
    std::cout << "\noriginal list now holds: ";
    for (auto str : s)
            std::cout << "\"" << str << "\" ";   //return nothing
    std::cout << '\n';
}

所以移动迭代器按预期移动.但是当我做了一些小改动时:

So the move iterator moves as expected. But when I made some minor changes:

    std::vector<int> s{1, 2, 3};
 
    std::vector<int> v1(s.begin(), s.end()); // copy
 
    std::vector<int> v2(std::make_move_iterator(s.begin()),
                                std::make_move_iterator(s.end())); // move

尽管移动了

s 仍然引用 {1, 2, 3}.这有什么原因吗?

s still references {1, 2, 3} despite moving. Is there a reason for this?

推荐答案

这些输出是预期的.在第一种情况下,您正在移动 std::string,这是一个定义了移动构造函数的对象.在第二种情况下,您正在移动 int,它只是一个数字,因此没有移动构造函数.

Those outputs are expected. In the first case, you are moving an std::string, which is an object that has a move constructor defined. In the second case, you are moving an int, which is just a number and therefore doesn't have a move constructor.

当您从 std::string 移动时,您的程序会将底层指针指向一个动态字符数组,并将该指针放入新字符串中.

When you move from the std::string, your program will take the underlying pointer to a dynamic character array and place that pointer into the new string.

当你从 int 移动时,你的程序不会做任何特别的事情,因为没有成员变量或任何可以移动的东西.所以实际上复制和移动 int 之间没有区别.

When you move from the int, your program won't do anything special because there are no member variables or anything to move around. So really there is no difference between copying and moving an int.

希望这是有道理的!如果您需要更多解释,请发表评论,我会尽力回答:)

Hopefully this makes sense! Leave a comment if you'd like more explanation and I'll try my best to answer :)

这篇关于C++ 移动迭代器和 int 向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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