Created
October 9, 2016 10:39
-
-
Save xplorld/2f0d8315233d46ef324f44888179afdc to your computer and use it in GitHub Desktop.
a C++ "enhanced" array from `T[]`
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
template <class T> | |
struct MyArray { | |
private: | |
T * arr; | |
size_t size; | |
public: | |
using type = T; | |
MyArray(size_t size) : | |
size(size), | |
arr(reinterpret_cast<T *>(new char[sizeof(T) * size])) { | |
new (arr) T[size]; | |
} | |
MyArray(const MyArray & other) : | |
size(other.size), | |
arr(reinterpret_cast<T *>(new char[sizeof(T) * other.size])) { | |
T * other_i = other.begin(); | |
for (size_t i = 0; i < size; ++i, ++other_i) { | |
new (arr+i) T(*other_i); | |
} | |
} | |
MyArray(MyArray && other) : MyArray(0) { | |
std::swap(this->size, other.size); | |
std::swap(this->arr, other.arr); | |
} | |
~MyArray() { | |
for (size_t i = 0; i < size; ++i) { | |
arr[i].~T(); | |
} | |
delete [] reinterpret_cast<char*>(arr); | |
} | |
T & operator[] (size_t index) { | |
if (index >= size) throw -1; | |
return arr[index]; | |
} | |
T* begin() const { | |
return arr; | |
} | |
T* end() const { | |
return arr + size; | |
} | |
}; | |
#include <iostream> | |
class Shouter { | |
public: | |
int i; | |
Shouter() : i(0) {std::cout << "default ctor " << i << std::endl;} | |
Shouter(int i) : i(i) {std::cout << "ctor " << i << std::endl;} | |
Shouter(Shouter const &other): i(other.i) {std::cout << "copy " << i << std::endl;} | |
Shouter(Shouter &&other): i(other.i) {std::cout << "move " << i << std::endl;} | |
~Shouter() {std::cout << "dele " << i << std::endl;} | |
}; | |
std::ostream &operator<<(std::ostream &os, Shouter const &m) { | |
return os << m.i; | |
} | |
int main() { | |
MyArray<Shouter> x(10); | |
for (int i = 0; i < 10; ++i) { | |
x[i].i = i; | |
cout << x[i] << endl; | |
} | |
auto y = std::move(x); //move | |
for (auto &i : y) { | |
cout << i << endl; | |
} | |
for (auto &i : x) { //produce nothing | |
cout << i << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment