# unique_ptr **Repository Path**: xukeawsl/unique_ptr ## Basic Information - **Project Name**: unique_ptr - **Description**: 自己实现一个单对象管理的unique_ptr,接口设计参考标准库 - **Primary Language**: C++ - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-04-04 - **Last Updated**: 2022-04-04 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 实现 C++ unique_ptr ## 测试代码 ```cpp #include "unique_ptr.h" #include #include #include using std::cout; using std::endl; struct Foo { Foo(int _val) : val(_val) { std::cout << "Foo...\n"; } ~Foo() { std::cout << "~Foo...\n"; } int val; }; class A { public: virtual void fun() noexcept { cout << "A" << endl; } virtual ~A() noexcept {} }; class B : public A { public: void fun() noexcept override { cout << "B" << endl; } }; int main(int argc, char* argv[]) { smt::unique_ptr p1; if (!p1) cout << "p1 is empty" << std::endl; smt::unique_ptr p2(nullptr); if (!p2) cout << "p2 is empty" << std::endl; smt::unique_ptr p3(new int(100)); cout << *p3 << endl; // 100 int* p = p3.release(); if (!p3) cout << *p << endl; // 100 delete p; p3.reset(new int(20)); cout << *p3 << endl; // 20 smt::unique_ptr up1(new Foo(1)); smt::unique_ptr up2(new Foo(2)); up1.swap(up2); cout << "up1->val:" << up1->val << endl; // 2 cout << "up2->val:" << up2->val << endl; // 1 Foo* pf = new Foo(3); up1.get_deleter()(pf); auto del = [](B* p) { cout << "destructor B" << endl; delete p; }; smt::unique_ptr bp(new B, del); bp->fun(); smt::unique_ptr bs(std::move(bp)); if (!bp) bs->fun(); // B smt::unique_ptr> fp(new A, [](A* p){ cout << "function A" << endl; delete p; }); auto fs(std::move(fp)); if (!fp) fs->fun(); // A fp = std::move(fs); // 注意需要析构器可复制, 而 lambda 闭包不可复制, 因此这里用 function 包装器 if (!fs) fp->fun(); std::vector> arr(5); for (int i = 0; i < 5; i++) { if (i & 1) { arr[i] = std::move(smt::unique_ptr(new B)); // 多态调用 } else { arr[i] = std::move(smt::unique_ptr(new A)); } cout << i << '-'; arr[i]->fun(); } return 0; } ```