未能理解有关std::move()的c++入门

failed to understand c++primer about std::move()

本文关键字:c++ 入门 move std 能理解      更新时间:2023-10-16

这本书C++Primer

重要的是要意识到,移动的调用承诺我们不打算再次使用rr1,除非分配给它或销毁它。

这是在线路之后:

int &&rr3 = std::move(rr1);

如何理解这句话?呼叫std::move(rr1)后rr1是否有任何更改?

有人认为这个问题已经在What is std::move()中得到了解决,什么时候应该使用它?但我不同意。这本书写着"我们可以销毁一个从中移出的对象,并可以为其分配一个新的值,但我们不能使用从中移出对象的值。"我不知道"我们不能使用移动的对象的值"是什么意思。有什么代码可以解释吗?

这个特定的代码示例没有切中要害。std::move对它所应用的对象没有任何作用。它只是一种不同的类型转换格式,其作用是在重要的情况下指导过载解决。例如:

void f(const my_type&);
void f(my_type&&);
my_type mm;
f(mm);            // calls f(const my_type&)
f(std::move(mm)); // calls f(my_type&&)

这很重要,因为采用右值引用的函数(在本例中为f(my_type&&))通常会对其参数做一些令人讨厌的事情,以使其工作更容易。例如,std::vector的复制构造函数复制传递给它的参数;move构造函数窃取参数的内部数组,使参数为空。因此,当你执行std::vector<int> vec(std::move(other_vector));时,除了分配或销毁它之外,你不应该对other_vector做任何事情,这就是"规则"所说的。

代码示例的问题在于,它对右值引用没有任何作用,因此,正如您所推断的,对象中没有任何变化,您可以继续使用它。但这是对std::move的愚蠢使用,也是一个毫无意义的示例。

move语义可以在对象内部动态分配内存时得到令人满意的理解。

class MemoryBlock  
{
    public:
    MemoryBlock(size_t length) : _length(length), _data(new int[length])  
    {  
    }  
    // copy constructor.  
    MemoryBlock(const MemoryBlock& other) : _length(other._length), _data(new int[other._length])  
    {   
        std::copy(other._data, other._data + _length, _data);  
    }  
    // move copy constructor.  
    MemoryBlock(MemoryBlock&& other) : _data(nullptr), _length(0)  
    {  
        // Copy the data pointer and its length from the source object.  
        _data = other._data;  
        _length = other._length;  
        // Release the data pointer from the source object.
        other._data = nullptr;  
        other._length = 0;  
    }  
    // destructor.  
    ~MemoryBlock()  
    {  
        if (_data != nullptr)  
        {  
              delete[] _data;  
        }
        _length = 0;  
    }  
    private:  
    size_t _length; // The length of the resource.  
    int* _data; // The resource.  
};
// ok, 'a' has 20 byte memory inside it.
MemoryBlock a(20); 
// we are literally transferring the memory from 'a' to 'b' by using move copy constructor.
MemoryBlock b = std::move(a); 
// so you broke the promise: "that we do not intend to use object 'a' again" after it has been moved. 
// a::_data is now null and code will break.
MemoryBlock c = a; 
//when object 'a' will go out of scope it can be destroyed properly
//this will work because the promise holds: "that object can be destroyed" after it has been moved.
//this will work, since you are copying the memory inside of 'd' to 'a' using normal copy constructor.
//so you obeyed the promise: "that we can assign to object 'a'" after it has been moved.
MemoryBlock d(30); 
MemoryBlock a = d;