Skip to content

Instantly share code, notes, and snippets.

@lucidfrontier45
Last active September 25, 2021 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucidfrontier45/ebd8ceacb17a92e0461c2deb09b3ffd6 to your computer and use it in GitHub Desktop.
Save lucidfrontier45/ebd8ceacb17a92e0461c2deb09b3ffd6 to your computer and use it in GitHub Desktop.
Test Copy and Move constructor
#include <iostream>
struct MyVector {
size_t current_size = 0;
size_t capacity = 0;
double* data = nullptr;
MyVector() : capacity { 10 }, current_size { 0 }
{
std::cout << "default constructor" << std::endl;
data = new double[capacity];
}
MyVector(const MyVector& other)
{
std::cout << "copy constructor" << std::endl;
capacity = other.capacity;
current_size = other.current_size;
data = new double[capacity];
for (size_t i = 0; i < capacity; i++) {
data[i] = other.data[i];
}
}
MyVector(MyVector&& other) noexcept
{
std::cout << "move constructor" << std::endl;
capacity = other.capacity;
current_size = other.current_size;
data = other.data;
other.capacity = 0;
other.current_size = 0;
other.data = nullptr;
}
~MyVector()
{
delete[] data;
data = nullptr;
}
double operator[](size_t i)
{
return data[i];
}
void push_back(double x)
{
if (capacity == 0) {
data = new double[capacity];
} else if (current_size == capacity) {
capacity = capacity * 2;
auto new_data = new double[capacity];
for (size_t i = 0; i < current_size; i++) {
new_data[i] = data[i];
}
delete[] data;
data = new_data;
}
data[current_size + 1] = x;
current_size += 1;
}
};
int main()
{
MyVector v1;
v1.push_back(1);
v1.push_back(2);
MyVector v2 { v1 };
std::cout << "v1.current_size = " << v1.current_size << " data addr = " << v1.data
<< std::endl;
std::cout << "v2.current_size = " << v2.current_size << " data addr = " << v2.data
<< std::endl;
MyVector v3 { std::move(v1) };
std::cout << "v1.current_size = " << v1.current_size << " data addr = " << v1.data
<< std::endl;
std::cout << "v3.current_size = " << v3.current_size << " data addr = " << v3.data
<< std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment