2014年01月14日 星期二 16:43
shared_ptr是C++11标准中的智能指针(smart pointer)之一,通过使用shared_ptr,我们可以尽量减少手工维护动态内存,减少错误的发生。
代码示例如下,需要使用符合C++11标准的编译器编译:
#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;
int main() {
auto p1=make_shared<string>("Good evening");
if(p1) {
cout << *p1 << endl;
}
shared_ptr<string> s(new string("Good afternoon"));
if(s) {
cout << *s << endl;
}
shared_ptr<vector<int>> p2(new vector<int>);
for(int i=0;i<10;i++) {
p2->push_back(i);
}
for(auto x : *p2) {
cout << x << "\t";
}
cout << endl;
auto p3(p2);
p3->push_back(100);
for(auto x : *p2) {
cout << x << "\t";
}
cout << endl;
cout << "p2 use_count: " << p2.use_count() << endl;
auto v=new vector<shared_ptr<string>>();
auto str=make_shared<string>("Good morning");
cout << "str use_count: " << str.use_count() << endl;
v->push_back(str);
cout << "str use_count: " << str.use_count() << endl;
delete v;
cout << "str use_count: " << str.use_count() << endl;
if(str.unique()) {
cout << "str is unique, reset it." << endl;
str.reset();
cout << "now str is null: " << str << endl;
}
return 0;
}
参考资料:
Zeuux © 2025
京ICP备05028076号