Skip to content

Instantly share code, notes, and snippets.

@barbu110
Created March 17, 2019 07:45
Show Gist options
  • Save barbu110/0fb7b19c3466d38cbefec9a7ab8eed43 to your computer and use it in GitHub Desktop.
Save barbu110/0fb7b19c3466d38cbefec9a7ab8eed43 to your computer and use it in GitHub Desktop.
MoveSemanticsExercise created by victorbarbu - https://repl.it/@victorbarbu/MoveSemanticsExercise
#pragma once
#include <iostream>
#include <cstring>
#include <string>
#ifndef debug
#define debug false
#endif
#define print_debug(msg) \
if (debug) { \
std::cout << "debug: " << msg << std::endl; \
}
class Data {
public:
Data(): size{0}, data{nullptr} {
print_debug("default constructor called");
}
Data(const char *str) {
print_debug("c-string constructor called");
size = std::strlen(str) + 1;
data = new char[size];
std::memcpy(data, str, size);
}
Data(const Data &other) {
print_debug("copy constructor called");
size = strlen(other.data) + 1;
data = new char[size];
memcpy(data, other.data, size);
}
Data(Data&& other): Data() {
print_debug("move constructor called");
swap(*this, other);
}
~Data() {
print_debug("destructor called");
delete[] data;
}
friend void swap(Data& first, Data &second) {
print_debug("custom swap function called");
using std::swap;
swap(first.data, second.data);
}
Data& operator=(Data other) {
swap(*this, other);
return *this;
}
int size;
char *data;
};
#include <iostream>
#define debug true
#include "data.h"
using namespace std;
Data foo() {
return Data{"moved?"};
}
int main() {
auto a1 = foo();
auto b1 = a1;
auto b2{foo()};
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment