Skip to content

Instantly share code, notes, and snippets.

@phg1024
Created October 17, 2015 07:05
Show Gist options
  • Save phg1024/e7d9fdf2a8f87db15a6d to your computer and use it in GitHub Desktop.
Save phg1024/e7d9fdf2a8f87db15a6d to your computer and use it in GitHub Desktop.
Simple vector
#include <iostream>
#include <vector>
using namespace std;
const int trunk_size = 8 * 1024 * 1024;
class A {
public:
static int counter;
A() { id = counter++; cout << "alloc " << id << " @ " << this << endl; trunk.resize(trunk_size); }
A(int size) { id = counter++; cout << "alloc " << id << " @ " << this << endl; trunk.resize(size); }
A(const A& other) : trunk(other.trunk) { id = counter++; cout << "cpy " << id << endl; }
A& operator=(const A& other) { id = counter++; trunk = other.trunk; cout << "assign " << id << " @ " << this << endl; }
~A() { cout << "dealloc " << id << " @ " << this << endl; }
private:
int id;
vector<char> trunk;
};
int A::counter = 0;
template <typename T>
struct simple_vector {
simple_vector() : cap(0), sz(0), t(nullptr) {}
simple_vector(int n) : cap(n*2), sz(0) {
t = static_cast<T*>(std::malloc(sizeof(T)*cap));
}
~simple_vector() {
for(int i=0;i<sz;++i) { t[i].~T(); }
std::free(t);
}
void push_back(const T& e) {
if(sz==cap) {
reserve(cap*2);
}
new(t+sz) T(e);
++sz;
}
void pop_back() {
if (sz > 0) {
back().~T();
--sz;
}
}
T& front() { return t[0]; }
T& back() { return t[sz-1]; }
void reserve(int n) {
if(n>cap) {
T* new_t = static_cast<T*>(std::malloc(sizeof(T)*n));
if(new_t != nullptr) {
t = new_t;
std::copy(t, t+sz, new_t);
} else {
cerr << "Out of memory." << endl;
exit(-1);
}
}
}
private:
int cap;
int sz;
T* t;
};
int main() {
cout << "begin" << endl;
{
vector<A> v(3);
}
{
A a[3] = {A(), A(), A()};
}
{
simple_vector<A> v(10);
for(int i=0;i<8;++i)
v.push_back(A(trunk_size));
cout << "before pop back" << endl;
char dummy;
cin >> dummy;
for(int i=0;i<5;++i)
v.pop_back();
cout << "after pop back" << endl;
cin >> dummy;
}
cout << "out of scope." << endl;
char dummy;
cin >> dummy;
cout << "end" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment