Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Last active August 19, 2021 08:26
Show Gist options
  • Save dboyliao/af55df76e967226e7590be1d5843b018 to your computer and use it in GitHub Desktop.
Save dboyliao/af55df76e967226e7590be1d5843b018 to your computer and use it in GitHub Desktop.
move semantic example code
cpp_move_example

Compile

# fail, the move constructor/operator are removed
$ make -e EXP_ENABLE_COPY=0
# compile, add required move constructor/operator
$ make -e EXP_ENABLE_COPY=1
#include <stdlib.h>
#include <iostream>
using std::cout;
using std::endl;
class DataPool {
public:
DataPool() : _size(0), _data(nullptr) {
cout << "default constructor: " << this << endl;
}
DataPool(size_t n) : _size(n) {
_data = new int[n];
if (_data == nullptr) {
_size = 0;
} else {
cout << _size << " of integers are allocated: " << this << endl;
}
}
~DataPool() {
if (_data != nullptr) {
cout << "cleanup data: " << this << endl;
delete[] _data;
}
}
int* data() const { return _data; }
// move semantic support
#if EXP_ENABLE_COPY
DataPool(DataPool&& other) {
cout << "I like to move it move it: " << this << endl;
if (_data != nullptr) {
delete[] _data;
}
_data = other._data;
_size = other._size;
other._data = nullptr;
other._size = 0;
}
DataPool& operator=(DataPool&& other) {
cout << "You like to move it move it: " << this << endl;
if (_data != nullptr) {
delete[] _data;
}
_data = other._data;
_size = other._size;
other._data = nullptr;
other._size = 0;
return *this;
}
#endif
private:
DataPool(const DataPool& other);
DataPool& operator=(const DataPool& other);
int* _data;
size_t _size;
};
DataPool create_pool(size_t n);
int main(int argc, const char* argv[]) {
DataPool pool = create_pool(100);
cout << "pool data: " << pool.data() << endl;
DataPool pool2;
pool2 = std::move(pool);
if (pool.data() == nullptr) {
cout << "pool data has been moved!" << endl;
cout << "pool2 data: " << pool2.data() << endl;
}
return 0;
}
DataPool create_pool(size_t n) {
cout << "doing a lot of cool stuffs" << endl;
return DataPool(n);
}
cpp_move_example: cpp_move_example.cpp
g++ -fno-elide-constructors -std=c++11 -DEXP_ENABLE_COPY=$$EXP_ENABLE_COPY $^ -o $@
.PHONY: cpp_move_example
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment