Skip to content

Instantly share code, notes, and snippets.

@phg1024
Created July 15, 2014 19:54
Show Gist options
  • Select an option

  • Save phg1024/862e8bf86b3a2ea04e9f to your computer and use it in GitHub Desktop.

Select an option

Save phg1024/862e8bf86b3a2ea04e9f to your computer and use it in GitHub Desktop.
demo use of unique pointer
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
struct dummy_t {
dummy_t(){}
dummy_t(int v):val(v){
cout << "dummy " << val << " constructred." << endl;
}
~dummy_t(){
cout << "dummy " << val << " destructred." << endl;
}
int val;
};
vector<unique_ptr<dummy_t>> gen(int n) {
vector<unique_ptr<dummy_t>> v;
for(int i=0;i<n;++i){
v.emplace_back(unique_ptr<dummy_t>(new dummy_t(i)));
}
return v;
}
void g(const dummy_t* d) {
cout << "g: " << d->val << endl;
}
void gv(const vector<dummy_t*> &v) {
for(auto& x:v) {
g(x);
}
}
void f() {
cout << "calling f..." << endl;
auto v = gen(10);
for(auto& x : v) {
cout << x->val << endl;
}
vector<dummy_t*> vp;
for(auto& x : v) {
vp.push_back(x.get());
}
gv(vp);
cout << "leaving f..." << endl;
}
int main() {
cout << "main begin." << endl;
f();
cout << "main end." << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment