Guide
copy constructors and copy assignment operators
MemoryBlock(const MemoryBlock& other)
MemoryBlock& operator=(const MemoryBlock& other)
move constructors and move assignment operators
MemoryBlock(MemoryBlock&& other)
MemoryBlock& operator=(MemoryBlock&& other)
example_move
#include <iostream>
#include <stdio.h>
#include <utility>
#include <vector>
#include <string>
class MemoryBlock
{
public:
explicit MemoryBlock(size_t length)
: _length(length)
, _data(new int[length])
{
std::cout << "In MemoryBlock(size_t). length = "
<< _length << "." << std::endl;
}
~MemoryBlock()
{
std::cout << "In ~MemoryBlock(). length = "
<< _length << ".";
if (_data != nullptr)
{
std::cout << " Deleting resource.";
delete[] _data;
}
std::cout << std::endl;
}
MemoryBlock(const MemoryBlock& other)
: _length(other._length)
, _data(new int[other._length])
{
std::cout << "In MemoryBlock(const MemoryBlock&). length = "
<< other._length << ". Copying resource." << std::endl;
std::copy(other._data, other._data + _length, _data);
}
MemoryBlock& operator=(const MemoryBlock& other)
{
std::cout << "In operator=(const MemoryBlock&). length = "
<< other._length << ". Copying resource." << std::endl;
if (this != &other)
{
delete[] _data;
_length = other._length;
_data = new int[_length];
std::copy(other._data, other._data + _length, _data);
}
return *this;
}
size_t Length() const
{
return _length;
}
MemoryBlock(MemoryBlock&& other)
: _data(nullptr)
, _length(0)
{
std::cout << "In MemoryBlock(MemoryBlock&&). length = "
<< other._length << ". Moving resource." << std::endl;
_data = other._data;
_length = other._length;
other._data = nullptr;
other._length = 0;
}
MemoryBlock& operator=(MemoryBlock&& other)
{
std::cout << "In operator=(MemoryBlock&&). length = "
<< other._length << "." << std::endl;
if (this != &other)
{
delete[] _data;
_data = other._data;
_length = other._length;
other._data = nullptr;
other._length = 0;
}
return *this;
}
private:
size_t _length;
int* _data;
};
void TestSTLObject()
{
std::string str = "Hello";
std::vector<std::string> v;
v.push_back(str);
std::cout << "After copy, str is \"" << str << "\"\n";
v.push_back(std::move(str));
std::cout << "After move, str is \"" << str << "\"\n";
std::cout << "The contents of the vector are \"" << v[0]
<< "\", \"" << v[1] << "\"\n";
}
void TestMyObjectWithoutUseMove()
{
std::vector<MemoryBlock> v;
MemoryBlock mb1(25);
v.push_back(mb1);
}
void TestMyObjectWithUseMove()
{
std::vector<MemoryBlock> v;
MemoryBlock mb1(25);
v.push_back(std::move(mb1));
}
int main(int argc, char const *argv[])
{
TestMyObjectWithUseMove();
return 0;
}
rewrite move constructor
MemoryBlock(MemoryBlock&& other)
: _data(nullptr)
, _length(0)
{
*this = std::move(other);
}
Reference
History