std::unique_ptr是一种智能指针,它通过指针持有并管理另一对象(对其负责),并在unique_ptr离开作用域时释放该对象。 在发生下列两者之一时,用关联的删除器释放对象: 管理它的unique_ptr对象被销毁。 通过operator=或reset()赋值另一指针给管理它的unique_ptr对象。
#include <iostream> #include <memory> int main() { std::unique_ptr<int> ptr(new int(42)); if (ptr) std::cout << "重置前,ptr 为: " << *ptr << '\n'; ptr.reset(); (ptr ? (std::cout << "重置后,ptr 为: " << *ptr) : (std::cout << "重置后 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(new Res{"Hello, world!"});Res*res=up.get();std::...
voidswap(unique_ptr&other)noexcept; (since C++11) Swaps the managed objects and associated deleters of*thisand anotherunique_ptrobjectother. Parameters other-anotherunique_ptrobject to swap the managed object and the deleter with Return value ...
(7) 实现从 auto_ptr 到 unique_ptr 的构造或赋值。 unique_ptr<T[]> 的构造函数。 (略, 具体与 unique_ptr<T> 类似,细节处有略微差异) 例子(取自 cppreference.com) ...
(7) 实现从auto_ptr到unique_ptr的构造或赋值。 unique_ptr<T[]>的构造函数。 (略, 具体与unique_ptr<T>类似,细节处有略微差异) 例子(取自cppreference.com) #include<iostream>#include<memory>structFoo{// object to manageFoo() {std::cout<<"Foo ctor\n"; } ...
// a function consuming a unique_ptr can take it by value or by rvalue reference std::unique_ptr<D> pass_through(std::unique_ptr<D> p) { p->bar(); return p; } void close_file(std::FILE* fp) { std::fclose(fp); } int main() { std::cout << "unique ownership semantics ...
unique_ptr没有control block,deleter type(包括默认的std::default_delete)直接做在unique_ptr一起了...
更加详细的内容参阅cppreference: ①std :: unique_ptr构造 ②赋值 3.使用 1#include <iostream>2#include <memory>3usingnamespacestd;45//unique_ptr::get vs unique_ptr::release6intmain()7{8std::unique_ptr<int> foo;//foo - null9std::unique_ptr<int> bar;//bar - null10int* p =nullptr...
unique_ptr类型是 template< class T, class Deleter =std::default_delete<T> > class uni...