Skip to content

Instantly share code, notes, and snippets.

@senior-sigan
Created April 25, 2020 11:58
Show Gist options
  • Save senior-sigan/d527a3b76cd627e625116e64a0f1346f to your computer and use it in GitHub Desktop.
Save senior-sigan/d527a3b76cd627e625116e64a0f1346f to your computer and use it in GitHub Desktop.
#include <iostream>
void copy_mem(const int *from, int *to, int n) {
std::cout << "copy memory from " << from << " into " << to << std::endl;
for (int i = 0; i < n; i++) {
to[i] = from[i];
}
}
class Box {
public:
int n_;
int *arr_;
explicit Box(int n) : n_(n), arr_(new int[n]) {
std::cout << "New Box(" << n << ") at" << this << std::endl;
}
Box(const Box &box) : n_(box.n_), arr_(new int[box.n_]) {
std::cout << "Copy Box(" << box.n_ << ") from " << &box << " into " << this << std::endl;
copy_mem(box.arr_, arr_, box.n_);
}
Box(Box &&box) noexcept : n_(box.n_), arr_(box.arr_) {
std::cout << "Move from " << &box << " into " << this << std::endl;
box.arr_ = nullptr;
box.n_ = 0;
}
Box &operator=(const Box &box) {
if (this == &box) return *this; // self assignment check
std::cout << "Assignment operator " << this << "=" << &box << std::endl;
delete [] arr_;
arr_ = new int[box.n_];
copy_mem(box.arr_, arr_, box.n_);
n_ = box.n_;
return *this;
}
~Box() {
std::cout << "Delete ~Box(" << n_ << ") " << this << std::endl;
delete [] arr_;
}
};
int main() {
{
std::cout << "==========EXAMPLE 1=========" << std::endl;
// Copy constructor example
Box b(100);
Box b2 = b;
}
{
std::cout << "==========EXAMPLE 2=========" << std::endl;
// Assignment operator example
Box a(100);
Box a2(42);
a2 = a;
}
{
std::cout << "==========EXAMPLE 3=========" << std::endl;
// Self Assignment
Box c(13);
c = c;// wtf
}
{
std::cout << "==========EXAMPLE 4=========" << std::endl;
Box d(17);
assert(d.n_ == 17);
Box d2(std::move(d));
assert(d.n_ == 0);
assert(d.arr_ == nullptr);
assert(d2.n_ == 17);
}
std::cout << "FINISH" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment