实例代码:
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <memory>
using namespace std;
class A{
public:
A(){
}
~A(){
}
};
auto myfunc(){
return unique_ptr<string>(new string("I Love China!"));
}
int main()
{
unique_ptr<int> pi;
if (pi == nullptr){
cout << "pi目前还是空指针" << endl;
}
unique_ptr<int> pi2(new int(105));
unique_ptr<int> p1 = make_unique<int>(100);
auto p2 = make_unique<int>(200);
unique_ptr<int> pi22(new int(105));
unique_ptr<string> ps1(new string("I Love China!"));
unique_ptr<string> ps4;
unique_ptr<string> ps21(new string("I Love China!"));
unique_ptr<string> ps22 = std::move(ps21);
unique_ptr<string> ps31(new string("I Love China!"));
unique_ptr<string> ps32(ps31.release());
if (ps31 == nullptr){
cout << "ps31 被置空" << endl;
}
string * tempp = ps32.release();
unique_ptr<string> ps41(new string("I Love China!"));
ps41.reset();
if (ps41 == nullptr) {
cout << "ps41 被置空" << endl;
}
unique_ptr<string> ps42(new string("I Love China!"));
ps41.reset(ps42.release());
ps41.reset(new string("I Love China!"));
unique_ptr<string> ps51(new string("I Love China!"));
ps51 = nullptr;
unique_ptr<int[]> ptrarray(new int[10]);
ptrarray[0] = 12;
ptrarray[1] = 24;
unique_ptr<A[]> ptrarray1(new A[100]);
unique_ptr<string> ps71(new string("I Love China!"));
string* ps7 = ps71.get();
*ps7 = "This is a test!";
unique_ptr<string> ps81(new string("I Love China!"));
ps7 = ps81.get();
unique_ptr<int> pt1(new int(100));
*pt1 = 200;
unique_ptr<int[]> pt2(new int[10]);
unique_ptr<string> ps91(new string("I Love China1!"));
unique_ptr<string> ps92(new string("I Love China2!"));
std::swap(ps91, ps92);
ps91.swap(ps92);
unique_ptr<string> ps101(new string("I Love China1!"));
if (ps101){
cout << "ps101 不为空 " << endl;
}
ps101.reset();
if (ps101) {
cout << "ps101 不为空 " << endl;
}
else{
cout << "ps101 为空 " << endl;
}
shared_ptr<string> pss1 = myfunc();
unique_ptr<string> ps11(new string("I Love China!"));
shared_ptr<string> pss2 = std::move(pss1);
system("pause");
}