尽量使用 shared_ptr ,如果确定要使用 unique_ptr , 那么一定要保证多线程场景下 get() 在使用时进行了 ptr 的转移,否则极可能误操作导致崩溃。
std::cout << "Value: " << ptr1->GetValue() << std::endl; // 创建另一个 shared_ptr,共享 ptr1 所指向的对象 std::shared_ptr<MyClass> ptr2(ptr1); // 当 ptr1 和 ptr2 都离开作用域时,MyClass 对象会被自动释放 } // 2 共享 int main() { std::shared_ptr<MyClass> ptr = st...
template<class T> class unique_ptr { public: typedef T element_type; typedef element_ty...
std::unique_ptr是一个非常简单的类。从概念上讲,基本上就是这样:
(s)<<");\n";}~Res(){std::cout<<"Res::~Res();\n";}private:friendstd::ostream&operator<<(std::ostream&os,Resconst&r){returnos<<"Res { s = "<<std::quoted(r.s)<<"; }";}};intmain(){std::unique_ptr<Res>up(newRes{"Hello, world!"});Res*res=up.get();std::cout<...
get(); // 未定义行为,可能崩溃 // 解释:使用std::move后,ptr1不再拥有资源,直接使用ptr1.get()并尝试删除是错误的,因为此时它可能为nullptr。 // 避免直接使用new - 反例:直接使用new而不通过std::make_unique std::unique_ptr<int> ptr(new int(42)); // 不推荐 // 解释:尽管这样可以工作,但...
autoptr3 = ptr1->getShared(); std::cout <<"使用计数: "<< ptr1.use_count() << std::endl;// 输出 3 // ptr2和ptr3离开作用域,但对象不会被删除 } std::cout <<"使用计数: "<< ptr1.use_count() << std::endl;// 输出 1 ...
STL中的智能指针(Smart Pointer)及其源码剖析:std::unique_ptr 和std::auto_ptr一样,std::unique_ptr也是一种智能指针,它也是通过指针的方式来管理对象资源,并且在unique_ptr的生命期结束后释放该资源。 unique_ptr持有对对象的独有权 —— 两个unique_ptr不能指向一个对象,不能进行复制操作只能进行移动操作。
参数 (无) 返回值 指向被管理对象的指针,无被管理对象,则为nullptr。 示例 运行此代码 #include <iostream>#include <string>#include <memory>intmain(){std::unique_ptr<std::string>s_p(newstd::string("Hello, world!"));std::string*s=s_p.get();std::cout<<*s<<'\n';} ...
每当你需要将原始指针传递给一个C函数时,你都会用到它: