Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cassert>
- using namespace std;
- template <typename T>
- class ScopedPtr {
- public:
- ScopedPtr() = default;
- explicit ScopedPtr(T* raw_ptr) noexcept {
- ptr_ = raw_ptr;
- }
- explicit operator bool() const noexcept {
- if(!ptr_){
- return false;
- }else{
- return true;
- }
- }
- T& operator*() const {
- if(!ptr_){
- throw logic_error("Empty Raw Pointer"s);
- }else{
- return *ptr_;
- }
- }
- T* operator->() const {
- if(!ptr_){
- throw logic_error("Empty Raw Pointer"s);
- }else{
- return ptr_;
- }
- }
- ScopedPtr(const ScopedPtr&) = delete;
- ~ScopedPtr() {
- delete ptr_;
- }
- T* GetRawPtr() const noexcept {
- return ptr_;
- }
- T* Release() noexcept {
- T* ptr_helper = ptr_;
- ptr_ = nullptr;
- return ptr_helper;
- }
- private:
- T* ptr_ = nullptr;
- };
- int main() {
- {
- const ScopedPtr<int> empty_ptr;
- assert(!empty_ptr);
- const ScopedPtr<int> ptr_to_existing_object(new int(0));
- assert(ptr_to_existing_object);
- static_assert(noexcept(static_cast<bool>(ptr_to_existing_object)));
- }
- {
- string* raw_ptr = new string("hello");
- ScopedPtr<string> smart_ptr(raw_ptr);
- assert(&*smart_ptr == raw_ptr);
- try {
- ScopedPtr<int> empty_ptr;
- *empty_ptr;
- assert(false);
- } catch (const logic_error&) {
- } catch (...) {
- assert(false);
- }
- }
- {
- string* raw_ptr = new string("hello");
- ScopedPtr<string> smart_ptr(raw_ptr);
- assert(smart_ptr->data() == raw_ptr->data());
- try {
- ScopedPtr<string> empty_ptr;
- empty_ptr->clear();
- assert(false);
- } catch (const logic_error&) {
- } catch (...) {
- assert(false);
- }
- }
- {
- struct Object {
- Object() {
- cout << "Object is default constructed"s << endl;
- }
- void DoSomething() {
- cout << "Doing something"s << endl;
- }
- ~Object() {
- cout << "Object is destroyed"s << endl;
- }
- };
- ScopedPtr<Object> empty_smart_ptr;
- assert(!empty_smart_ptr);
- ScopedPtr<Object> smart_ptr(new Object());
- assert(smart_ptr);
- (*smart_ptr).DoSomething();
- smart_ptr->DoSomething();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment