标签:alt 输出 函数 返回 ima auto pre not info
对对象独有管理,无法复制,共享,值传递,可以使用move语义来转移控制权。
std::default_delete<int> d; std::unique_ptr<int> u1; std::unique_ptr<int> u2 (nullptr); std::unique_ptr<int> u3 (new int); std::unique_ptr<int> u4 (new int, d); std::unique_ptr<int> u5 (new int, std::default_delete<int>()); std::unique_ptr<int> u6 (std::move(u5)); std::unique_ptr<int> u7 (std::move(u6)); std::unique_ptr<int> u8 (std::auto_ptr<int>(new int)); std::cout << "u1: " << (u1?"not null":"null") << ‘\n‘; std::cout << "u2: " << (u2?"not null":"null") << ‘\n‘; std::cout << "u3: " << (u3?"not null":"null") << ‘\n‘; std::cout << "u4: " << (u4?"not null":"null") << ‘\n‘; std::cout << "u5: " << (u5?"not null":"null") << ‘\n‘; std::cout << "u6: " << (u6?"not null":"null") << ‘\n‘; std::cout << "u7: " << (u7?"not null":"null") << ‘\n‘; std::cout << "u8: " << (u8?"not null":"null") << ‘\n‘;
输出:
临时的unique_ptr可以赋值给非临时的unique_ptr,例如使用在函数返回值的时候:
unique_ptr<int> _int(int n) { return unique_ptr<int>(new int(n)); }
转移控制权:
auto ptr1 = make_unique<string>("123"); std::cout<<*ptr1<<std::endl; auto ptr2 = move(ptr1); std::cout<<*ptr2<<std::endl; std::cout<< (ptr1 == nullptr ? "null" : *ptr1) <<std::endl;
输出:
交换控制权:
std::unique_ptr<int> foo (new int(10)); std::unique_ptr<int> bar (new int(20)); foo.swap(bar); std::cout << "foo: " << *foo << ‘\n‘; std::cout << "bar: " << *bar << ‘\n‘;
输出:
重置:
std::unique_ptr<int> up; up.reset (new int); *up=5; std::cout << *up << ‘\n‘; up.reset (new int); *up=10; std::cout << *up << ‘\n‘; up.reset();
输出:
标签:alt 输出 函数 返回 ima auto pre not info
原文地址:https://www.cnblogs.com/tyche116/p/12074451.html