Skip to content

Instantly share code, notes, and snippets.

@munckymagik
Created August 31, 2019 07:13
Show Gist options
  • Save munckymagik/2c3ba83d3cae616679589ae088c3d864 to your computer and use it in GitHub Desktop.
Save munckymagik/2c3ba83d3cae616679589ae088c3d864 to your computer and use it in GitHub Desktop.
Trying out "moves" in C++
# Basic CMake project
cmake_minimum_required(VERSION 2.8.11)
# Name the project after the exercise
project(moving CXX)
set(CMAKE_CXX_FLAGS "-std=c++17 -Wall -Werror")
add_executable(moving moving.cpp)
#include <iostream>
#include <string>
using namespace std;
class Thing {
public:
Thing(const string label)
: label(label)
, instance(1)
{
log(__func__);
}
Thing(const Thing& other) {
*this = other;
log(string(__func__) + " copy");
}
Thing(const Thing&& other) {
*this = std::move(other);
log(string(__func__) + " move");
}
~Thing() {
log(__func__);
}
Thing& operator=(const Thing& other) {
if (this != &other) {
label = other.label;
instance = other.instance + 1;
}
log(__func__);
return *this;
}
Thing& operator=(const Thing&& other) {
if (this != &other) {
label = other.label;
instance = other.instance + 1;
}
log(string(__func__) + " move");
return *this;
}
const string& get_label() { return this->label; }
private:
void log(const string_view func) {
cout << "[" << func << "] " << label << instance << endl;
}
string label;
int instance;
};
Thing copy_thing(Thing t) {
cout << "[" << __func__ << "]" << endl;
return t;
}
void call_me(Thing& t) {
cout << "[" << __func__ << "(Thing& t)] " << t.get_label() << endl;
}
// void call_me(Thing t) {
// cout << "[" << __func__ << "] " << t.get_label() << endl;
// }
void call_me(Thing&& t) {
cout << "[" << __func__ << "(Thing&& t)] " << t.get_label() << endl;
}
int main() {
// Thing a1("a");
// cout << endl;
// Thing a2(a1);
// cout << endl;
// Thing a3 = a2;
// cout << endl;
// Thing a4 = std::move(a3);
// cout << endl;
// auto b1 = make_unique<Thing>("b");
// cout << endl;
// Thing c1("c");
// auto c2 = copy_thing(c1);
// cout << endl;
// auto d2 = copy_thing(Thing("d"));
// cout << endl;
auto a = Thing("a");
call_me(a);
cout << endl;
call_me(std::move(a));
cout << endl;
// copy_thing(a);
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment