【问题标题】:Int variable's value won't change after being movedInt 变量的值在移动后不会改变
【发布时间】:2015-08-03 16:58:44
【问题描述】:

我已经阅读了移动语义的基础知识并进行了一些测试。 案例一:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int  main()
{
    string st = "hello";
    vector<string> vec;
    vec.push_back(st);
    cout << st;

    cin.get();
}

在这种情况下,程序将不会打印任何内容,因为“hello”已移至 vector[0]。

案例#2:

#include <iostream>
#include <vector>

using namespace std;
int  main()
{
    int num=5;
    vector<int> vec;
    vec.push_back(num);
    cout << num;

    cin.get();
}

为什么程序打印“5”?我以为 num 会是 0 或未定义的东西。

【问题讨论】:

    标签: vector move-semantics


    【解决方案1】:

    案例#1 应该打印“hello”。如果没有,那么您的编译器有错误,您应该升级到新版本或向曾经编写它的人投诉。

    案例 #2 正确打印“5”。

    但是,如果您将案例 2 中的第 10 行更改为:

    vec.push_back(st);
    

    到:

    vec.push_back(std::move(st));
    

    你会得到你所期望的,打印到控制台的“”,因为向量“偷走了”st中的值。

    int 是 c++ 中的 fundamental type,试图从 int 变量中“窃取”并没有真正起作用,因为它不拥有任何资源。

    std::string 是资源所有者。它“拥有”一个 char 数组(这并不总是正确的,但为简单起见,我们会假装它是)。

    因此,当我们将std::move(st) 传递给push_back 时,我们调用了push_back 的T&& 重载,它通过调用std::string 的move constructor 来“窃取”,释放st 的句柄并将其提供给在 vec 中新创建的 std::string。

    但是如果我们这样调用 push_back:vec.push_back(st); 这不会“窃取”任何东西。相反,它将调用 push_back 的 const T& 重载,它只是通过调用 std::string 的普通复制构造函数来进行简单的复制,这样我们将 st 设置为“hello”,并将 vec[0] 设置为它自己的版本“你好”。

    试试下面的代码,看看效果如何:

    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    struct Foo
    {
        Foo() // default constructor
        {
            cout << "Foo()" << endl;
        }
        Foo(const Foo&) // copy constructor
        {
            cout << "Foo(const Foo&)" << endl;
        }
        Foo(Foo&&) // move constructor
        {
            cout << "Foo(Foo&&)" << endl;
        }
        Foo& operator=(const Foo&) // copy assignment operator
        {
            cout << "operator=(const Foo&)" << endl;
            return *this;
        }
        Foo& operator=(Foo&&) // move assignment operator
        {
            cout << "operator=(Foo&&)" << endl;
            return *this;
        }
        ~Foo()
        {
            cout << "~Foo()" << endl;
        }
    };
    int main()
    {
        Foo f; // print: Foo();
    
        vector<Foo> vec;
        vec.push_back(f); // print: Foo(const Foo&)
        vec.push_back(std::move(f)); // print: Foo(Foo&&)
    
        Foo f2; // print: Foo()
        f2 = f; // print: operator=(const Foo&)
        f2 = std::move(f); // print: operator=(Foo&&)
    
        cin.get();
    }
    

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 2022-11-27
      • 2023-03-21
      • 2015-06-17
      • 1970-01-01
      相关资源
      最近更新 更多