Created
March 17, 2019 07:45
-
-
Save barbu110/0fb7b19c3466d38cbefec9a7ab8eed43 to your computer and use it in GitHub Desktop.
MoveSemanticsExercise created by victorbarbu - https://repl.it/@victorbarbu/MoveSemanticsExercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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