Last active
October 4, 2017 07:59
-
-
Save othrayte/3138ca6f9a806ee76c210cd125c82804 to your computer and use it in GitHub Desktop.
A pointer thats is always owned and alway present
This file contains hidden or 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 <utility> | |
| // A pointer thats is always owned and alway present (and valid if new returns a valid pointer) | |
| // Should be useful if moving allocation of a member variable to the heap to enable use of forward declarations | |
| template <typename T> | |
| class local_ptr { | |
| public: | |
| template <typename... U> | |
| local_ptr(U&&... args) : ptr(new T(std::forward<U>(args)...)) {} | |
| // Non-copyable as owns the pointer, maybe you need a std::unique_ptr or std::shared_ptr | |
| local_ptr(const local_ptr<T>&) = delete; | |
| local_ptr<T>& operator=(const local_ptr<T>&) = delete; | |
| ~local_ptr() { delete ptr; } | |
| T* operator->() { return ptr; } | |
| const T* operator->() const { return ptr; } | |
| T& operator*() { return *ptr; } | |
| const T& operator*() const { return *ptr; } | |
| T* get() { return ptr; } | |
| const T* get() const { return ptr; } | |
| private: | |
| T* ptr; | |
| }; | |
| // Prove that local_ptr can be used with forward declarations | |
| struct A; | |
| struct Foo { | |
| Foo(); | |
| local_ptr<A> a; | |
| }; | |
| struct A { | |
| A(double v) : x(v), y(v), z(v) {}; | |
| double x,y,z; | |
| double sum() { return x + y + z; } | |
| }; | |
| Foo::Foo() : a(2.0) {}; | |
| struct Bar { | |
| Bar() : a(2) {}; | |
| A a; | |
| }; | |
| int main() { | |
| // Prove that the type we are using is 'big' | |
| static_assert(sizeof(A) == sizeof(double)*3); | |
| // Prove that the local_ptr is 'small' | |
| static_assert(sizeof(local_ptr<A>) == sizeof(void*)); | |
| // Prove that Bar contains a whole 'big' A | |
| static_assert(sizeof(Bar) == sizeof(A)); | |
| // Prove that Foo contains only a 'small' pointer | |
| static_assert(sizeof(Foo) == sizeof(void*)); | |
| // Prove that the constructor can be called | |
| local_ptr<A> a(2); | |
| // Prove that the local_ptr can'y be copied | |
| //local_ptr<A> b(a); // Can't copy | |
| //local_ptr<A> c(2); | |
| //c = a; // Can't copy | |
| // Prove that member functions can still be called | |
| return a->sum(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment