Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <memory>
- #include <iostream>
- struct A {
- A() { std::cout << "A" << std::endl; }
- ~A() { std::cout << "~A " << b << std::endl; }
- int b = 0;
- };
- template <class T>
- class UniquePtr {
- public:
- explicit UniquePtr(T* ptr) : ptr_(ptr) {}
- ~UniquePtr() { delete ptr_; }
- // Запрещаем копирование
- UniquePtr(const UniquePtr& other) = delete;
- UniquePtr& operator=(const UniquePtr& other) = delete;
- UniquePtr(UniquePtr&& other) : ptr_(other.ptr_) { other.ptr_ = nullptr; }
- UniquePtr& operator=(UniquePtr&& other) {
- std::swap(ptr_, other.ptr_);
- return *this;
- }
- UniquePtr& operator=(T* other) {
- if(other != ptr_) {
- delete ptr_;
- ptr_ = other;
- }
- return *this;
- }
- T& operator* () { return *ptr_;}
- const T& operator* () const { return *ptr_; }
- T* operator-> () { return ptr_;}
- const T* operator-> () const { return ptr_;}
- private:
- T* ptr_ = nullptr;
- };
- void f(bool throw_exception)
- {
- // A a;
- UniquePtr<A> pa(new A());
- (*pa).b = 5;
- pa->b = 6;
- pa = new A();
- if(throw_exception)
- throw std::runtime_error("error");
- }
- int main() {
- try {
- f(false);
- f(true);
- } catch(const std::exception& exc) {
- std::cout << "g-exception happened: " << exc.what();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement