move语义如何与unique

move语义如何与unique

本文介绍了move语义如何与unique_ptr一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使用 unique_ptr ,并写了一些简单的代码来检查它如何与move语义一起使用。

I was experimenting with using unique_ptr and wrote some simple code to check how it works with move semantics.

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

class X
{
public:
    X(){}
    ~X() { cout << "Destructor X" << endl; }
    void Print() { cout << "X" << endl; }
};

int main()
{
    unique_ptr<X> ptr(new X());
    ptr->Print();

    vector<unique_ptr<X>> v;
    v.push_back(move(ptr));
    ptr->Print();
    v.front()->Print();

    return 0;
}

输出如下:

X
X
X
Destructor X

我的期望是,原来的unique_ptr ptr 会在push_back之后失效。但是Print()方法被调用就好了。这种行为的解释是什么?

My expectation was that the original unique_ptr ptr would be invalidated after the push_back. But the Print() method is called just fine. What would be the explanation for this behavior?

推荐答案

它设置为空指针。您可以通过将其与 nullptr 比较来检查。

It's set to a null pointer. You can check that by comparing it to nullptr.

您正在对一个空指针调用一个成员函数,这是一个未定义的行为。该成员函数实际上不访问类中的任何数据,所以它不会崩溃,但它仍然是未定义的行为。

You're calling a member function on a null pointer, which is undefined behaviour. That member function doesn't actually access any data in the class, so it doesn't crash, but it's still undefined behaviour.

你会得到类似的行为,它与 unique_ptr 无关:

You get similar behaviour for this program, it has nothing to do with unique_ptr:

int main()
{
  X x;
  X* ptr = &x;
  ptr->Print();
  ptr = nullptr;
  ptr->Print();
}

看起来工作正常,因为 X :: Print ()实际上不会从 this 指针中读取任何内容。如果你改变 X :: Print()的定义来访问类中的一些成员数据,你可能会因为取消引用一个空指针而崩溃。

It appears to work fine because X::Print() doesn't actually read anything from the this pointer. If you change the definition of X::Print() to access some member data in the class you'll probably get a crash due to dereferencing a null pointer.

请参阅有关更多信息。

这篇关于move语义如何与unique_ptr一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:09