【问题标题】:C++ move iterator and int vector [duplicate]C ++移动迭代器和int向量[重复]
【发布时间】:2020-08-01 00:05:52
【问题描述】:

我试图理解移动迭代器。这是来自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';
}

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

    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} 尽管移动。这是有原因的吗?

【问题讨论】:

  • 移动ints 没有多大意义,因此移动与复制几乎相同。我也不建议在移动对象后尝试使用它们。您从移动对象获得的唯一保证是您可以安全地销毁它。绝对不保证它包含的内容。

标签: c++ vector move


【解决方案1】:

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

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

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

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

【讨论】:

  • 轻微调整:没有动态内存或任何可以移动的东西内存不需要是动态的。
  • @user4581301 很好的说明。为了解释这句话,我引用了std::string 维护动态内存这一事实,并指出intstd::string 的不同之处在于它没有。
  • 明白。但另一个有趣的事实:也不能保证 std::string 包含动态内存。 See Short String Optimization
  • 哦,太棒了!感谢您的链接,这是一个非常聪明的概念:O
猜你喜欢
  • 1970-01-01
  • 2011-07-04
  • 2013-12-16
  • 1970-01-01
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
相关资源
最近更新 更多