Created
November 14, 2018 09:59
-
-
Save revsic/929711112b08de61f8736a1f7826b67d to your computer and use it in GitHub Desktop.
Box = unique_ptr + buffer size
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> | |
template <typename T> | |
class Box { | |
public: | |
Box(size_t size) : ptr(new T[size]), size(size) { | |
// Do Nothing | |
} | |
Box(T* ptr, size_t size) : ptr(ptr), size(size) { | |
// Do Nothing | |
} | |
~Box() { | |
reset(); | |
} | |
Box(const Box&) = delete; | |
Box(Box&& box) : ptr(box.ptr), size(box.size) { | |
box.ptr = nullptr; | |
} | |
Box& operator=(const Box&) = delete; | |
Box& operator=(Box&& box) { | |
reset(); | |
ptr = box.ptr; | |
size = box.size; | |
box.ptr = nullptr; | |
return *this; | |
} | |
void reset(T* other = nullptr) { | |
if (ptr != nullptr) { | |
delete[] ptr; | |
} | |
ptr = other; | |
} | |
T* release() { | |
T* released = ptr; | |
ptr = nullptr; | |
return released; | |
} | |
void swap(Box<T>& other) { | |
std::swap(ptr, other.ptr); | |
std::swap(size, other.size); | |
} | |
operator bool() { | |
return ptr != nullptr; | |
} | |
T* get() { | |
return ptr; | |
} | |
const T* get() const { | |
return ptr; | |
} | |
T& operator*() { | |
return *ptr; | |
} | |
const T& operator*() const { | |
return *ptr; | |
} | |
T& operator[](size_t idx) { | |
return ptr[idx]; | |
} | |
const T& operator[](size_t idx) const { | |
return ptr[idx]; | |
} | |
T* begin() { | |
return ptr; | |
} | |
const T* begin() const { | |
return ptr; | |
} | |
T* end() { | |
return ptr + size; | |
} | |
const T* end() const { | |
return ptr + size; | |
} | |
private: | |
T* ptr; | |
size_t size; | |
}; | |
int main() { | |
auto box = Box<int>(10); | |
for (size_t i = 0; i < 10; ++i) { | |
box[i] = i; | |
} | |
for (auto const& elem : box) { | |
std::cout << elem << std::endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment