未能理解有关std::move()的c++入门
failed to understand c++primer about std::move()
这本书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;
相关文章:
- C++入门 5 版:类消息和文件夹
- 代码编译没有任何输出,入门程序
- C++ 任务流库入门
- C++入门5版:使用get成员初始化另一个与shared_ptr无关的对象
- Mujoco 的入门步骤:缺少具有 Simulate.cpp 的共享库
- C++ 入门 12.1:我可以在类中使用静态向量成员实现 StrBlob<string> 吗?
- C++ 入门 5 版:流迭代器和Sales_item
- C++ 入门加列表:10.9 "顶部"指针问题
- 不确定有关入门C++参考的描述
- 无法导入 Boost.Python 创建的 dll(按照 Boost Python 的快速入门)
- TinyXML2 - 入门时遇到问题
- C++谷歌入门练习#4
- 继承入门C++问题
- C++入门加第 2 章练习 3
- C++ 入门加上第 2 章 EX7 - 无法解决
- 未能理解有关std::move()的c++入门
- Boost.Python 快速入门链接器错误
- 为什么这个C++代码(来自C++入门5th 3.4.2)不能正常工作?
- 视觉C++入门练习 1.19,首次尝试"if"语句
- 视觉C++入门练习 1.12 结果令人困惑